基本的 C 问题 - 当你在 C 中声明一个静态变量时到底发生了什么?

Basic c question - What exactly happens when you declare a static variable in c?

我正在尝试了解静态变量在给定函数中定义时如何在 c 中工作。例如,当我写以下内容时:

#include <stdio.h>
void inc() {
  static int c = 0;
  c++;
  printf("%d\n", c);
}

int main(void) {
  inc();
  inc();
  inc();
  return 0;
}

预期的输出显然是:

1
2
3

在函数的第一次调用中,静态变量c被定义并赋值为0,这是非常合理的。它是递增和打印的。然而,在第二次调用 inc() 时,为什么整数 c 被保留而不是设置为零,即使代码字面意思是 static int c = 0;。编译器中的什么机制阻止 c 在第一次调用时将其值设置为零?

引用 C11,章节 §6.2.4,对象的存储持续时间(强调我的

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

因此,函数调用内部的初始化不会在每次调用函数时都发生。它只发生一次,在 main() 开始执行之前。变量通过程序执行保留最后存储的值,即在重复调用函数之间保留值。

它的生命周期是程序的整个执行过程,它的值在程序启动前被初始化并且只有一次。