在C函数中的静态变量 [英] Static variable inside of a function in C
问题描述
void foo()
{
static int x = 5;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
什么将被打印出来? 6 6 6或7
What will be printed out? 6 6 or 6 7
为什么?
推荐答案
有两个问题在这里,寿命和范围。
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()的返回;所以它会被重新初始化到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.
关键字静态行为来扩展变量的程序的生存的生存期;例如初始化发生一次,只有一次,然后该变量保留其值 - 不管它来是 - 在所有未来调用到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屋!