Search code examples
cprogram-entry-pointstack-frame

What happens to stack Frames when main() calls main()


Please consider the following code:

#include <stdio.h>

int main()
{
    static int counter=5;

    printf ("Counter = %d\n", counter);

    if (counter--)
    {
        main();
    }

    return 0;
}

Compile:

gcc test.c -ansi -Wall –pedantic

Execute:

[root@mars home]# ./a.out 
Counter = 5
Counter = 4
Counter = 3
Counter = 2
Counter = 1
Counter = 0

Here main() is calling itself().

It seems that main() function's original stackframe will be overwritten each time main() is called by itself.

But what will be the return address? Can a function return to its own stackframe?

Please help me clarify this doubt.

Thanks.


Solution

  • No it is not overwritten. It is a normal function call (in this case recursive). You are probably confused by your counter variable. This variable is declared static, which means that it is initialized only once, so the line below is "executed" only once:

    static int counter=5;
    

    In other words you can think of your counter as if it was a global variable initialized only once (with the value 5). In each invokation of main it is decremented until it reaches zero. After that happens all the main functions return, so the stack is unwinded (as in normal function call which it is).