为什么 static 修饰符会阻止其变量被重新分配新值?

Why does the static modifier prevent its variable to be reassigned with a new value?

一个最小的工作示例如下:

#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

Static变量的修饰符int使得int的值永久存在整个过程的静态存储不存储在堆栈中;因此,该值从函数的一次调用传递到另一次调用。

但是intfunc()开始时重新赋值为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, but 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.

您很可能对等号感到困惑,=

static int i = 5;中的等号表示copy initialisation,不是赋值:

The equals sign, =, in copy-initialization of a named variable is not related to the assignment operator.

因此,

However, int is re-assigned to the value of 5 at the beginning of func()

这是错误的。在 func 的开头 从未分配 ,无论是第一次还是以后的调用。 i = 42;赋值。

你也可以这样写:

static int i(5);