是否在C中默认将全局结构的成员初始化为零? [英] Are the members of a global structure initialized to zero by default in 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屋!