Search code examples
cstaticoutputstorage-class-specifier

Storage classes: Understanding Static


I am not able to understand the output of this program-

int main()
{
    static int i=5;
    if(--i) {
        main();
        printf("%d ",i);
    }
}

The output is 0 0 0 0

My doubt is why wont static be initialized in the first call to main? The output if I assume static gets initialized in the first call to 5, and then gets shared between calls should be 4 3 2 1

Thanks!


Solution

  • The call to main() is called recursively 4 times before any printf() statement is called. By the time the first printf() gets called, --i has been called recursively 4 times. Since i is static, its value is 0 at that point and that's the value that is printed.