in Programming in C
453 views
2 votes
2 votes
#include <stdio.h>

int main()
{

   static int i = 6;
    if(--i)
    {
        main();
        printf("%d", i+1);
    }
    return 0;
}

Please explain the output of this program ?
in Programming in C
453 views

1 Answer

6 votes
6 votes

Ans will be 11111. If you understand how static variable works then you will get the idea.

Static Variables in C - GeeksforGeeks

Note: Because of static keyword, whenever you will call a new function(main in this case) the variable i will get updated(--i) but the variable is not local to the function call , due to static key word memory will be created at compile time in stack area.You are calling functions at run time , and every function call will use the same address which is being created at compile time for i. When i will become 0 if condition will be false function we will go back to the caller function and will print (i+1) and value of i is 0. We have called main five times(if(5) to if(1)) so 5 times 1 will be printed.

Related questions