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?