[英]Initialization of a local static variable throught multiple function calls
int f(int &g){
static int a=g;
a+=1;
return a;
}
int main()
{
int g=0;
int a=f(g);
g=10;
a=f(g);
cout<<a;
return 0;
}
The above code gives output 2. What my guess was that it should be 11.上面的代码给出了输出 2。我的猜测是它应该是 11。
I do understand that the a
in main function is not the same as that in f function.我确实明白 main 函数中的a
与 f 函数中的 a 不同。 So when g=0
, a in f would be 1, I believe.所以当g=0
,a in f 将是 1,我相信。 Then when g=10
, it should be 11, giving a=11
in main.然后当g=10
,它应该是 11,在 main 中给出a=11
。 Why isn't that the case?为什么不是这样? Thanks!谢谢!
You are misinterpreting the static
keyword here.您在这里误解了static
关键字。 When a local variable is declared static
, it is initialized once.当一个局部变量被声明为static
,它会被初始化一次。 Inside of the function, this is when then function is called the first time.在函数内部,这是第一次调用 then 函数的时间。 You first call this function in你首先调用这个函数
int g=0;
int a=f(g);
The local variable a
inside f
is hence initialized to zero and then incremented.因此, f
内部的局部变量a
被初始化为零,然后递增。 Later on, you call f
a second time,稍后,你第二次调用f
,
g=10;
a=f(g);
but as the local variable is already initialized, it is not overwritten.但由于局部变量已经初始化,它不会被覆盖。 Instead, the second increment takes place, resulting in the value of 2
.相反,发生第二次增量,结果为2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.