C中函数内部的静态变量 [英] Static variable inside of a function in C

查看:25
本文介绍了C中函数内部的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

会打印出什么?6 6 还是 6 7?为什么?

What will be printed out? 6 6 or 6 7? And why?

void foo()
{
    static int x = 5;
    x++;
    printf("%d", x);
}

int main()
{
    foo();
    foo();
    return 0;
}

推荐答案

这里有两个问题,生命周期和作用域.

There are two issues here, lifetime and scope.

变量的作用域是可以看到变量名的地方.这里,x 仅在函数 foo() 中可见.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

变量的生命周期是它存在的时间段.如果x 没有定义关键字static,生命周期将从进入foo() 到从foo() 返回;所以它会在每次调用时重新初始化为 5.

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

关键字 static 用于将变量的生命周期延长到程序的生命周期;例如初始化只发生一次,然后变量保留它的值——不管它变成了什么——在以后对 foo() 的所有调用中.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

这篇关于C中函数内部的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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