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.
No it is not overwritten. It is a normal function call (in this case recursive). You are probably confused by your
countervariable. This variable is declared static, which means that it is initialized only once, so the line below is “executed” only once:In other words you can think of your
counteras if it was a global variable initialized only once (with the value 5). In each invokation ofmainit is decremented until it reaches zero. After that happens all themainfunctions return, so the stack isunwinded(as in normal function call which it is).