c - 访问不活跃的 union 成员

标签 c c99 unions

如果我有以下代码:

#include <stdint.h>
union data_t {
  int8_t sbyte;
  uint8_t ubyte;
  int16_t sint;
  uint16_t uint;
  int32_t slong;
  uint32_t ulong;
  int64_t sint64;
  uint64_t uint64;
  float qsingle;
  double qdouble;
  long double qfloat;
};
union data_t *data;
data = malloc(sizeof(union data_t));
data.uint = 2534;

在这里,我已将 uint16_t 类型指定为 42,我可以安全地访问比我指定的数据类型更小的数据类型(例如 uint8_t),并安全地对其进行类型转换(至 230)?这个答案 ( Accessing inactive union member and undefined behavior? ) 似乎说它在 C11 中是允许的,但我不确定这在 C99 中是否合法。

最佳答案

此问题的答案在 C99 C11 中没有明确定义。在这两个标准中,§6.2.6.1p7 说:

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.

我肯定会在设置不同的成员后访问 qsingleqdoubleqfloat 成员时遇到问题。这些成员可能具有导致引发信号(例如 SIGFPE)的表示,并且从此类信号处理程序返回是未定义的行为。

关于c - 访问不活跃的 union 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16984932/

相关文章:

c - 未知类型名称 'siginfo_t' 与使用 _POSIX_C_SOURCE 2 的 Clang,为什么?

union 中的 C 对齐

c++ - C 和 C++ 的 union 函数指针初始化

c++ - 如何解释 int 中分配的 float 内存来模拟乘法?

c - 是否可以在c中使用serialport类?

c - 没有 typedef 关键字的结构

c++ - 为什么 memmove 比 memcpy 快?

c - fread 在接受所有用户输入(来自标准输入)之前终止

c - 将多维可变长度数组传递给函数

c - 指针或值