静态整数

Jos*_*osh 1 c++ static scope

我想知道静态是如何工作的.这是一个例子:

void count()
{
    static int x = 1;
    cout << "Static: " << x << endl;
    x++;

    return;
}

int main()
{
    //Static variable test
    cout << endl;
    count();
    count();
}
Run Code Online (Sandbox Code Playgroud)

该程序输出"1和2".但我想知道第二次调用函数"count"时,为什么不执行"static int x = 1"行?

Fre*_*Foo 6

这是一种语言规则; static变量的初始化只执行一次.

请注意,这与...不同

static int x;
x = 1;
Run Code Online (Sandbox Code Playgroud)

x每次通话都会重置为1.