一个最小的工作示例如下:
#include <iostream>
void func()
{
static int i = 5;
std::cout << i << std::endl;
i = 42;
std::cout << i << std::endl;
}
int main( int argc, char ** argv )
{
std::cout << "this is main()" << std::endl;
func();
func();
return 0;
}
其输出如下:
this is main()
i is 5
i is 42
i is 42
i is 42
变量 int 的 Static 修饰符使 int 的值在整个进程的生命周期内保持不变,而静态存储不存储在堆栈;因此,该值从函数的一次调用传递到另一次调用。
但是,int 在 func() 开始时被重新赋值为 5,当 func() 被第二次调用时时间。
那么,为什么这个例子输出的是 i = 42
而不是 i = 5
?
最佳答案
However, int is re-assigned to the value of 5 at the beginning of func() when func() is called second time.
不,这不是assignment , 但是 initialization . Static local variables仅初始化一次,即在第一次调用 func()
时。
Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.
关于c++ - 为什么 static 修饰符会阻止其变量被重新分配新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43435792/