其中一些可能是重复的,但我很抱歉。
假设我有这个 struct
:
struct foo
{
int a;
int b;
int c;
};
1. 如果struct foo
类型的对象声明为具有自动存储持续时间且没有 初始化器,是否保证它的所有成员都将被强制初始化为零吗?
{
// other stuff
struct foo bar;
// other stuff
}
2. 如果struct foo
类型的对象以自动存储持续时间和一些初始化器的方式声明,是否有保证未显式初始化的成员将被强制初始化为零?
{
// other stuff
struct foo bar = {.a = 1};
// other stuff
}
3. 如果struct foo
类型对象以自动存储期的方式声明,并使用复合字面量表达式,是它保证未显式初始化的成员将被强制初始化为零?
{
// other stuff
func((struct foo){.a = 1});
// other stuff
}
非常感谢任何 C 标准引用!谢谢!
最佳答案
总结,长话短说:
存储期限说明:
- 在函数内声明的变量具有自动存储持续时间(包括函数的参数)。
- 声明为
static
的变量,或在文件作用域(“全局”)的外部函数声明的变量具有静态存储持续时间。
结构(和数组)初始化解释:
- 如果您未初始化任何成员且该结构具有自动存储持续时间,则不会初始化任何内容。
- 如果您未初始化任何成员并且该结构具有静态存储持续时间,则所有成员都将被零初始化。
- 如果您初始化任何成员,则您未接触的成员将被初始化为零。
C标准的相关部分(C17 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;
其中“artihmetic type”是普通变量的标准乱码,如 int
,而“aggregate”是数组和结构的标准乱码。
在同一章的后面(C17 6.7.9 §19):
...all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.
问题的答案:
- If struct foo type object is declared in the way that it has automatic storage duration and without initializers, is it guaranteed that all it's members will be force initialized to zero?
不,不能保证;正如上面引用的第一句所述,它们的值是不确定的。
- If struct foo type object is declared in the way that it has automatic storage duration and with some initializers, is it guaranteed that members, which are not explicitly initialized, will be force initialized to zero?
是的,根据上面引用的 C17 6.7.9 §19。
- If struct foo type object is declared in the way that it has automatic storage duration and by using compound literal expression, is it guaranteed that members, which are not explicitly initialized, will be force initialized to zero?
是的,因为复合文字是数组或结构,所以它们遵循相同的初始化规则。
关于c - 自动存储持续时间结构初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52205008/