gpt4 book ai didi

c - 在 C 中,全局结构的成员是否默认初始化为零?

转载 作者:太空狗 更新时间:2023-10-29 16:25:09 27 4
gpt4 key购买 nike

C 中的全局或静态结构的成员是否保证自动初始化为零,与uninitialized global or static variables are 的方式相同? ?

最佳答案

来自 C99 标准 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

由于全局和静态结构具有静态存储持续时间,所以答案是肯定的——它们是零初始化的(结构中的指针将被设置为 NULL 指针值,通常是零位,但严格来说不需要是)。

C++ 2003 标准有类似的要求(3.6.2“非局部对象的初始化”):

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.

在零初始化发生后的某个时间,构造函数将根据更复杂的规则调用(如果对象具有构造函数),这些规则控制这些调用的时间和顺序。

关于c - 在 C 中,全局结构的成员是否默认初始化为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4080673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com