我遇到了一个小谜题,我试图找到它的输出。一旦我设法获得输出,我调整了 1 行,输出就完全不同了。为什么以下两个程序的输出不同?:
一)
#include<stdio.h>
int fun()
{
static int num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
输出:
38 35 32 29 26 23 20 17 14 11 8 5 2
二)
#include<stdio.h>
int fun()
{
static int num;
num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
输出:无限循环每次打印40
只有一个区别:声明和初始化在 (a) 中同时进行,但在 (b) 中分开进行。这对最终结果有何影响?
最佳答案
static int num = 40;
static int num;
这些都被评估一次。 num
不存在于运行时堆栈中(而是存在于数据段中)然后,
num = 40;
每次调用 fun()
时都会进行评估。您将在堆栈外声明的变量重新分配给 40,导致它永远循环。
关于c - 堆和栈段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22052789/