请考虑以下代码:
编译:
#include <stdio.h>
int main()
{
static int counter=5;
printf ("Counter = %d\n", counter);
if (counter--)
{
main();
}
return 0;
}
编译:
gcc test.c -ansi -Wall –pedantic
执行:
[root@mars home]# ./a.out
Counter = 5
Counter = 4
Counter = 3
Counter = 2
Counter = 1
Counter = 0
这里的 main() 函数在调用自身。
似乎每次 main() 被自身调用时,原始的堆栈帧都会被覆盖。
但是返回地址将是什么?函数能够返回到自己的堆栈帧吗?
请帮我澄清这个疑问。
谢谢。
int counter
被声明为static
,因此它不会被分配在函数的栈上,而是在全局堆上分配。 - alk