c - 是否保证 c 结构的成员被初始化为 0?

标签 c

当我在 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/

相关文章:

将 char 指针数组转换为 void 指针,然后再转换回来

c - 如何使用 getpwuid_r() 正确设置缓冲区和 bufsize?

c - 在c中使用堆栈和指针

c++ - 使用 getch() 进行标准输入时输入 EOF 符号

c - 为什么链接错误类型的函数不会返回垃圾?

c - 函数 localtime() 是如何使用的?

c - gdb 意外行为 : in nested if

c - 文件 NULL 不会被循环遗忘 - C

c - 为什么 GCC 包含一个 "empty"XOR

CGo 将 go 字符串转换为 *C.uchar