#include <stdio.h>
int main()
{
static int i = 5;
if(--i){
main();
printf("%d,", i);
}
return 0;
}
I'm unable to find why the value of i
is becoming 0 every time.
#include <stdio.h>
int main()
{
static int i = 5;
if(--i){
main();
printf("%d,", i);
}
return 0;
}
I'm unable to find why the value of i
is becoming 0 every time.
There is a recursive call to main()
in your code, till if(--i)
is not down to 0. The print statement does not get a chance to execute.
Once i
becomes zero, the control returns, and the value of i
, is, well, 0, then.
[I don't have a photo editor handy right now, sorry],
Try to have a look at the rough graphics to get an idea.
FWIW, i
is having static
storage, so it holds the value across function calls.
(I assumed the last part is already understood, just adding for sake of clarity.)
here's your program's execution and values:
i = 5; --i; main ()// i==4
i = 4; --i; main ()// i==3
i = 3; --i; main ()// i==2
i = 2; --i; main ()// i==1
i = 1; --i; // i == 0 ,main is not called!
and only then the program comes back from recursion:
printf("%d,", i);