静态变量的赋值被忽略

Assignment to static variable is ignored

我有以下代码:

#include <stdio.h>

int f1()
{
    static int s=10;
    printf("s=%d\n",s++);
}
int main()
{
    f1();
    f1();
    return 0;
}

输出为:

s=10
s=11

为什么在调用 f1 时第二次忽略行 static int s=10

静态变量的初始化是一次性的(初始化时间保证发生在第一次调用之前,这可能发生在编译时或 运行 时间;取决于编译器)。这是使用它们的主要原因。

static 变量仅初始化一次,从概念上讲甚至在应用程序启动之前。

来自 C11 (N1570) §5.1.2/p1 执行环境:

All objects with static storage duration shall be initialized (set to their initial values) before program startup.

连同 §6.2.4/p3 对象的存储持续时间:

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

那不是赋值,而是一个初始化程序。局部 static 变量像全局变量一样只在程序启动时初始化一次。即使在函数调用之间,它们也会保留最后的 assigned 值。因此,在您第一次调用后,它会保留值 11。事实上,它们就像文件范围的 static 变量,它们的名字只在它们被声明的块范围内已知(但你可以通过指针传递它们)。

缺点是它们只存在一次。如果您从多个线程调用相同的函数,它们将共享 相同的 变量。

尝试第三次调用:你会得到 12

注意:初始化器必须是常量表达式。尝试 static int s = 10, t = s + 5; 并阅读编译器错误消息。

正如其他人所说,函数范围内的 static 变量仅初始化一次。所以赋值不会在后续调用该函数时发生。

与其他局部变量不同,static 局部变量不是在堆栈上而是在数据段中定义的,可能与全局变量位于同一位置。全局变量也在应用程序启动时初始化(它们必须这样做,因为它们不存在于函数内部,因此不能成为可执行代码),因此从概念上讲,您可以将 static 变量视为全局变量能见度有限。

来自 C89 标准 HTML version at 3.1.2.4 对象的存储持续时间 它指定:

An object declared with external or internal linkage, or with the storage-class specifier static has static storage duration. For such an object, storage is reserved and its stored value is initialized only once, prior to program startup. The object exists and retains its last-stored value throughout the execution of the entire program

(重点是我的)

因此它表示每次使用静态限定符时,该变量都会在多个函数调用中保留其值。 非静态的局部变量会在您每次调用对它们进行 delcares 处理的函数时进行初始化,因此它们不会在函数调用中保留它们的值。

希望对您有所帮助!