局部静态变量如何在方法中工作?

4 c static function

下面是我的代码:

//main.c

int f()
{
    static int x = 0;
    x += 1;
    return x;
}

int main()
{
   f();
   printf("%d", f());
}
Run Code Online (Sandbox Code Playgroud)

并且输出是2

我知道静态变量会保持状态,但是由于我调用了f()两次,每次x都先设置为 0 ( static int x = 0;),然后加 1,那么1无论我调用多少次,输出都应该是f()

Ing*_*rdt 6

static变量不仅依然存在,他们只有一次初始化,所以x不是“每次都设置为0至上”,它仍然1在第二个电话,然后得到增加。确实如此

static int x = 0;  // x is initialized once only
Run Code Online (Sandbox Code Playgroud)

static int x;
x = 0; // x is set to 0 with every call
Run Code Online (Sandbox Code Playgroud)