1
votes

I came across a small puzzle for which I was trying to find the output. Once I managed to get the output, I tweaked in 1 line and the output is totally different. Why does the output of the following two programs vary?:

a)

#include<stdio.h>
int fun()
{
  static int num = 40;
  return num--;
}

int main()
{
  for(fun(); fun(); fun())
  {
    printf("%d ", fun());
  }
  getchar();
  return 0;
}

Output:

38 35 32 29 26 23 20 17 14 11 8 5 2

b)

#include<stdio.h>
int fun()
{
  static int num;
  num  = 40;
  return num--;
}

int main()
{
  for(fun(); fun(); fun())
  {
    printf("%d ", fun());
  }
  getchar();
  return 0;
}

Output: Infinite loop printing 40 everytime

There is just one difference: The declaration and initialization are done at the same time in (a) but separately in (b). How does that effect the final outcome?

4
Why do you use the title (and related tags for) 'Heap and Stack segment' in your question, but don't mention them at all in the body itself? Do you know what they are? Was it mentioned in the 'puzzle'?ArjunShankar

4 Answers

3
votes
static int num = 40;

static int num;

These both get evaluated once. num does not live on the runtime stack (but rather in the data segment) Then,

num = 40;

gets evaluated every time you call fun(). You're reassigning a variable that was declared outside the stack to 40, causing it to loop forever.

2
votes

In the first one, num will only be initialised to 40 the first time the function is called. In the second one, it is set to 40 every time the function is called.

1
votes

first one, num gets initialized once, no matter how many times you call the function

second one, num gets set to 40 every time you call the function

0
votes

Two concepts need to be looked into here

  1. lifetime of variable
  2. scope of variable

The lifetime of a variable is the period over which it exists. If num were defined without the keyword static, the lifetime would be from the entry into fun() to the return from fun(); so it would be re-initialized to 40 on every call.

The scope of variable is where the variable name can be seen. Here, num is visible only inside function fun().

The keyword static is used to extend the lifetime of a variable to the lifetime of the program. In case of static declaration initialization occurs only once and then the variable retains its value inside the routine fun(). So if you are overwriting it by setting it to value of 40 in the second case its values keeps getting set to 40 on every call to fun(). The declaration of the variable num as static is redundant in your second code.