c - 使用 clang 与 gcc 进行 union 零初始化

标签 c gcc initialization clang unions

给出以下 C 代码:

union Test {
  struct {
    int f1;
    int f2;
  };

  struct {
    int f3;
    int f4;
    int f5;
  };
};

union Test test = {.f1 = 1, .f2 = 2};

当我用 gcc 6.1.1 编译它时,f5 将被零初始化。当我使用 clang 3.8.0 时,情况并非如此。我尝试对两个编译器使用 -O0-O2 ,但没有任何区别。这是在 Linux x64 上。

哪种行为是正确的?在这种情况下我可以告诉 clang 像 gcc 那样行为吗?原因是我尝试使用 clang 编译一些代码,在这种情况下假设零初始化。

更新

由于到目前为止的答案都引用了 C11。标准中是否有任何更改改变了后续版本中的行为?

最佳答案

C11在第 6.2.6.1.7 节中指定:

When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.

您通过第一个结构访问 union 体,访问第二个结构的成员可能会产生未指定的值,因此 clang 没有错误,gcc 也没有。


更新:C11 中添加了匿名成员。指定的 init 出现在 C99 中。

关于c - 使用 clang 与 gcc 进行 union 零初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226837/

上一篇:c - select() 不等待

下一篇:CRC位序困惑

相关文章:

c++ - CoCreateInstance - 反过来是什么?

linux -/usr/bin/ld : attempted static link of dynamic object `/usr/lib64/libm.so'

gcc - 内联警告

c++ - 如何在 C++ 中使用默认参数初始化 "unsigned char *"?

c - 汇编:如何将 float 扩展为 double 以便使用 sin 函数

c - 线程和并行编程

c++ - 实例化结构体字段时的默认值

c++ - 在cpp文件中初始化一个私有(private)静态成员变量。错误 : member is private

c - 这个数据报套接字有什么问题?

gcc - 成功构建了 GCC 交叉编译器工具链。如何正确设置环境变量?