C中静态变量的初始化

The initialization of static variables in C

我有一个关于C中静态变量初始化的问题,我知道我们是否声明了一个全局静态变量,默认值是0。例如:

1
static int a; //although we do not initialize it, the value of a is 0

但是下面的数据结构呢?

1
2
3
4
5
6
7
8
typedef struct
{
    int a;
    int b;
    int c;
} Hello;

static Hello hello[3];

hello[0]hello[1]hello[2]的每个结构中的所有成员是否初始化为0


是的,所有成员都是为具有静态存储的对象初始化的。参见C99标准(PDF文件)中的6.7.8/10

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these
rules.

为了初始化一个对象中的所有内容,不管它是不是static到0,我喜欢使用通用的零初始值设定项

1
2
3
sometype identifier0 = {0};
someothertype identifier1[SOMESIZE] = {0};
anytype identifier2[SIZE1][SIZE2][SIZE3] = {0};

C中没有部分初始化。对象要么已完全初始化(在没有其他值的情况下完全初始化为正确类型的0),要么根本未初始化。如果要进行部分初始化,则不能从初始化开始。

1
2
3
int a[2]; // uninitialized
int b[2] = {42}; // b[0] == 42; b[1] == 0;
a[0] = -1; // reading a[1] invokes UB

是的,文件范围静态变量初始化为零,包括结构、数组等的所有成员。

请参阅此问题以供参考(我也会投票将其作为副本关闭)。

编辑:这个问题得到了更好的答案,所以我投票决定将这个问题作为这个问题的副本来结束。

作为参考,这里是来自该问题公认答案的C FAQ链接,当然这里链接的C99和C11标准是规范的。


是的,只要它们有静态或线程存储持续时间就可以。

C11 (n1570), § 6.7.9 Initialization #10

If an object that has static or thread storage duration is not initialized
explicitly, then:

[...]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules,
    and any padding is initialized to zero bits;

[...]


我要补充的是,静态变量(或数组)分为两种类型。

初始化是在编译时从代码中给定值的代码。这些通常存储在DS中,尽管这是特定于编译器的。

另一种类型是未初始化的静态类型,这些静态类型在运行时初始化并存储到BSS段中,尽管这也是编译器特有的。

盲源分离