全局结构的成员在 C 中是否默认初始化为零? [英] Are the members of a global structure initialized to zero by default in C?
问题描述
C 中全局或静态结构的成员是否保证自动初始化为零,就像 未初始化的全局或静态变量是?
Are the members of a global or static structure in C guaranteed to be automatically initialized to zero, in the same way that uninitialized global or static variables are?
推荐答案
来自C99标准6.7.8/10初始化":
From the C99 standard 6.7.8/10 "Initialization":
如果一个对象具有自动存储持续时间未初始化明确地,它的价值是不定.如果一个对象有静态存储持续时间不是显式初始化,然后:
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
由于全局和静态结构具有静态存储期,所以答案是肯定的——它们是零初始化的(结构中的指针将被设置为 NULL 指针值,通常为零位,但严格来说不需要是).
Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).
C++ 2003 标准有类似的要求(3.6.2非本地对象的初始化"):
The C++ 2003 standard has a similar requirement (3.6.2 "Initialization of non-local objects"):
具有静态存储持续时间 (3.7.1) 的对象应在进行任何其他初始化之前进行零初始化 (8.5).
Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.
在零初始化发生后的某个时间,根据更复杂的规则调用构造函数(如果对象有构造函数),这些规则控制这些调用的时间和顺序.
Sometime after that zero-initialization takes place, constructors are called (if the object has a constructor) under the somewhat more complicated rules that govern the timing and ordering of those calls.
这篇关于全局结构的成员在 C 中是否默认初始化为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!