c - 自动存储持续时间结构初始化

标签 c struct initialization language-lawyer automatic-storage

其中一些可能是重复的,但我很抱歉。
假设我有这个 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.


问题的答案:

  1. 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?

不,不能保证;正如上面引用的第一句所述,它们的值是不确定的。

  1. 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。

  1. 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/

相关文章:

c - 如何安全地将两个可变大小的数据类型(结构)放在一个结构中?

ios - NSData 到 Struct 搞乱数据

java - 为什么我可以在java中创建一个0行5列的二维数组?

c - 理解c中的按位补码

c - 我的 C 程序如何知道在哪里可以找到我的二进制库?

go - 在结构映射中实现结构集

variables - 使用 np.zeros 和使用 tf.zeros 初始化 Tensorflow 变量之间的区别

c - 指向未初始化变量的指针

c - 带有可变参数的 scanf(C 语言)

C fgets() - 只将文件的最后一行写入数组?