当我在 C 中声明一个结构时,我是否保证成员将被初始化为某个特定值,例如整数成员为 0?
编辑:
那么,假设我有一个如下所示的结构:
typedef struct
{
int a;
} my_str;
我声明:
my_str thing1;
全局。根据一些答案,thing1.a 将初始化为 0 - 我理解正确吗?
最佳答案
C99标准的相关部分:
第 6.2.4 节,§3:
An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
第 6.2.4 节,§4:
An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration.
第 6.2.4 节,§5(关于具有自动存储持续时间的对象):
The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.
第 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.
关于c - 是否保证 c 结构的成员被初始化为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1505101/