堆栈上的结构 - 字段已初始化?

structure on the stack - fields initialized?

考虑以下代码:

void func()
{
   int p;
   ...
   if (p > MAX) {
       struct my_struct s;
       ...
       /* here we access the contents 's' as '&s' */
   }
}

在此代码段中,s 在堆栈上。是否保证编译器将所有结构字段初始化为零?

不,恰恰相反。

由于s是一个自动存储的局部作用域(即块作用域)变量,除非明确初始化,否则内容为不确定

引用 C11,章节 §6.7.9

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...].

然而,如果你想对一个(y)聚合类型的变量进行零初始化,你可以简单地使用像

这样的初始化语句
aggregate-type variable = {0};

其中使用了同一章第 21 段中的以下 属性,(强调我的

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

不,它们根本不会被初始化。结构值将以放置结构的堆栈中的任何垃圾结束。

如果变量(struct 或其他)被声明为函数或包含范围的局部变量(即具有自动存储持续时间),则它不会以任何方式初始化。您需要明确设置 struct 中的字段。

如果你至少初始化一个结构体的一个字段而不是全部,那么其余字段将被初始化为文件范围变量(即具有静态存储持续时间的变量),这意味着 NULL 用于指针类型和数字类型为 0。

来自 C standard 的第 6.7.9 节:

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread 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, and any padding is initialized to zero bits;

— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

...

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

struct my_struct s;
       ...
       /* here we access the contents 's' as '&s' */

这里你没有静态变量,你有一个自动变量,所以没有预初始化。

另一方面,如果您使用优化进行编译,则无法保证编译器将此变量存储在何处,除非您检查汇编程序的输出,这不是由 C 语言定义的。