在 c 中工作的静态存储类 [英] static storage class working in c

查看:13
本文介绍了在 c 中工作的静态存储类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者,所以请多多包涵.最近,我开始阅读 C 中的存储类,偶然发现了这个问题:

I'm a beginner so please bear with me. Recently, I started reading storage classes in C and I stumbled upon this question:

#‎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.

This program outputs : 14 11 8 5 2.

1) 谁能告诉我这段代码是如何工作的?

1) Can any please tell me how does this code work?

2) 当我将 --num 保留在 fun() 中时,它正在运行一个无限循环.为什么会这样?

2) When I keep --num in fun() ,it is running an infinite loop. Why it happens like that?

推荐答案

static int num = 16; 表示 num 会被初始化为 16 而不会被函数返回时销毁.

static int num = 16; means that num will be initialized as 16 and it will not be destroyed when the function returns.

return num--; 表示将返回 num 值,但之后 num 值将减少并保存,因为 num 被声明为 static.

return num--; means that num value will be returned but after that num value will be decreased and saved because num is declared as static.

我用数字标记了对 fun() 的不同调用(只是为了遵循执行流程,而不是用作真正的代码)所以它可以显示如何变量 num正在改变.

I MARKED different calls to fun() with numbers (just to follow execution flow, not to be used as real code) so it could be shown how variable num is changing.

for(fun1(); fun2(); fun4())
    printf("%d \n", fun3());

fun1() 在初始化时仅被调用"一次.fun2() 是一个控制表达式,如果结果为零则 for 循环停止执行.fun3() 每次在循环中被调用".fun4() 每次循环结束时被调用"

fun1() "is called" only once as initialization. fun2() is a control expression, if the result is zero than execution of for loop stops. fun3() "is called" each time in the loop. fun4() "is called" each time at the end of loop"

价值观如何变化:

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.

If you change num-- to --num than for loop control expression (marked as fun2()) never gets 0.

这篇关于在 c 中工作的静态存储类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆