我是初学者,所以请多多包涵。最近,我开始阅读 C 中的存储类,我偶然发现了这个问题:
#include<stdio.h>
int fun()
{
static int num = 16;
return num--;
}
int main()
{
for(fun(); fun(); fun())
printf("%d \n", fun());
return 0;
}
这个程序输出:14 11 8 5 2。
1) 谁能告诉我这段代码是如何工作的?
2) 当我在 fun() 中保留 --num 时,它正在运行一个无限循环。为什么会这样?
最佳答案
static int num = 16;
表示num
会被初始化为16,并且不会在函数返回时销毁。
return num--;
表示 num
值将被返回,但之后 num
值将减少并保存,因为 num
声明为 static
。
我用数字标记了对 fun()
的不同调用(只是为了遵循执行流程,而不是用作真实代码)所以它可以显示变量 num
在改变。
for(fun1(); fun2(); fun4())
printf("%d \n", fun3());
fun1()
仅在初始化时“被调用”一次。 fun2()
是一个控制表达式,如果结果为零则 for
循环停止执行。 fun3()
每次在循环中“被调用”。 fun4()
“每次在循环结束时都被调用”
值(value)观是如何变化的:
fun1() called
num: 16
fun2() called
num: 15
fun3() called
num: 14
14
fun4() called
num: 13
fun2() called
num: 12
fun3() called
num: 11
11
fun4() called
num: 10
fun2() called
num: 9
fun3() called
num: 8
8
fun4() called
num: 7
fun2() called
num: 6
fun3() called
num: 5
5
fun4() called
num: 4
fun2() called
num: 3
fun3() called
num: 2
2
fun4() called
num: 1
fun2() called
num: 0 ==> stop
如果将 num--
更改为 --num
而不是 for
循环控制表达式(标记为 fun2()
) 永远不会得到 0。
关于c - 在c中工作的静态存储类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181396/