在c中工作的静态存储类
我是初学者,请容忍我。最近,我开始阅读C语言的存储类,我偶然发现了这个问题: 在c中工作的静态存储类,c,storage,C,Storage,我是初学者,请容忍我。最近,我开始阅读C语言的存储类,我偶然发现了这个问题: #包括 int fun() { 静态int num=16; 返回数值--; } int main() { 为了(乐趣();乐趣();乐趣()) printf(“%d\n”,fun()); 返回0; } 该程序输出:1411852 1) 能告诉我这个代码是怎么工作的吗 2) 当我在fun()中保持--num时,它正在运行一个无限循环。为什么会发生这种情况?首先,我希望您知道C中的存储类是什么。现在,当我们处理静
#包括
int fun()
{
静态int num=16;
返回数值--;
}
int main()
{
为了(乐趣();乐趣();乐趣())
printf(“%d\n”,fun());
返回0;
}
该程序输出:1411852
1) 能告诉我这个代码是怎么工作的吗
2) 当我在fun()中保持--num时,它正在运行一个无限循环。为什么会发生这种情况?首先,我希望您知道C中的存储类是什么。现在,当我们处理静态变量时,该变量会一直持续到程序结束并存储在数据段中。静态变量的一些特征如下: 存储=内存 默认初始值=零 Scope=定义变量的块的局部 寿命=变量的值在不同的函数调用之间持续存在 现在来回答你的问题
static int num=16
表示num
将被初始化为16,并且在函数返回时不会被销毁
returnnum--
表示将返回num
值,但此后num
值将减少并保存,因为num
声明为static
我用数字标记了对fun()
的不同调用(只是为了跟随执行流,而不是用作实际代码),以便显示变量num
是如何变化的
for(fun1(); fun2(); fun4())
printf("%d \n", fun3());
fun1()
“仅作为初始化调用一次fun2()
是一个控制表达式,如果结果为零,则执行for
循环停止<每次在循环中调用“code>fun3()”fun4()
“被称为“每次在循环结束时”
值是如何变化的:
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。此网站上有一篇文章介绍了静态变量:
但基本上,静态变量在程序的整个生命周期中保持其值
我将与您一起逐步介绍代码,但将来使用gdb进行此操作的一个很好的资源是:
至于为什么当return--num;
是fun()中的最后一行时它不运行,这是因为for循环中的条件语句永远不会收到0(0,只有0为false,每隔一个数字为true)。程序的输出将是:13、10、7、4、1、-2等;这意味着条件语句将接收:14、11、8、5、2、-1等。当使用--num
时,您将得到一个无限循环,因为fun
从不返回0
我的意思是在for循环的条件下它不会返回0
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
int fun()
{
static int num = 16; /* Essentially this line is only seen once by the program.
** The 'num' variable keeps its value for the life of the program.
*/
return num--; /* Returns the value of 'num' and *afterwards* subtracts 1 from 'num'. */
}
int main()
{
for(fun(); fun(); fun())
printf("%d \n", fun()); /* This line runs the for loop until 'num' == -1, as the
** condition is fun(), which is true while it returns a
** value > 0. fun() is run twice when the loop starts, once in
** the intialising part of for() (the first term), then once by
** the conditional term (the middle term). From there on it is
** run once by the printf(), once by the updating term
** (the end term), and once by the conditional term,
** until the conditional term is not fulfilled.
*/
return 0;
}