用C未初始化结构 [英] Uninitialized Structures in C
问题描述
在C全局或静态结构的成员的保证被自动初始化为零,在同样的方式,<一href=\"http://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value\">uninitialized全局或静态变量的?
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屋!