2
#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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Recursive `main()`.... I don't like _weird_ things.. :) – Sourav Ghosh Dec 30 '15 at 14:59
  • 1
    It becomes zero because you decrease it? Is the problem perhaps your understanding about how `static` local variables work? Maybe is a problem understanding recursion? To better understand the recursion you should learn how to use a debugger and how to step over code line by line, and more importantly step *into* function calls. Do that and it will become clear. – Some programmer dude Dec 30 '15 at 15:00
  • Switch the 2 lines in the if and see what happens – 001 Dec 30 '15 at 15:01
  • Write out the code line-by-line, replacing `main` with the code that will actually get executed, so you end up with 1 procedural function. It'll make sense – Elias Van Ootegem Dec 30 '15 at 15:02
  • I tried @Johnny Mopp it is giving output as 4, 3, 2, 1 – sabhitha vangaveti Dec 30 '15 at 15:04
  • 1
    There is little point having a `static int` in `main` unless it recurses, which is *unwise behaviour*. – Weather Vane Dec 30 '15 at 15:04
  • Correct. You do understand that static variables only get initialized once? They are kind of like global variables in lifetime but only have local scope. – 001 Dec 30 '15 at 15:06

2 Answers2

3

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.

enter image description here

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.)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

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);
Or Yaniv
  • 571
  • 4
  • 11