更新时间:2022-05-05 22:54:21
这里有两个问题,生命周期和作用域.
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()
.