我有一个关于 C 中静态变量初始化的问题。我知道如果我们声明一个默认值为 0
的全局静态变量。例如:
static int a; //although we do not initialize it, the value of a is 0
但是下面的数据结构呢:
typedef struct
{
int a;
int b;
int c;
} Hello;
static Hello hello[3];
hello[0]
, hello[1]
, hello[2]
中的所有成员都初始化为 0
?
最佳答案
是的,所有成员都为具有静态存储的对象初始化。参见 C99 Standard (PDF document) 中的 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,我喜欢使用通用零初始化程序
sometype identifier0 = {0};
someothertype identifier1[SOMESIZE] = {0};
anytype identifier2[SIZE1][SIZE2][SIZE3] = {0};
C 中没有部分初始化。一个对象要么被完全初始化(在没有不同值的情况下为正确类型的 0
),要么没有被初始化全部。
如果您想要部分初始化,则不能从一开始就进行初始化。
int a[2]; // uninitialized
int b[2] = {42}; // b[0] == 42; b[1] == 0;
a[0] = -1; // reading a[1] invokes UB
关于c - C中静态变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251083/