c++ - 类型双关——编译器如何决定使用什么类型?

标签 c++ unions type-punning

我正在阅读 this question here about deciding endianness第一个答案让我有些困惑。

判断big endianness的代码如下:

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } bint = {0x01020304};

    return bint.c[0] == 1; 
} 

我的问题是此处的编译器如何决定为该十六进制数字数组使用什么类型?因为从技术上讲,它同样适用于 uint32_tchar[4]

为什么不直接将其存储在 char[4] 中并跳过 union

union 有什么我看不到的优点吗?我知道这叫做类型双关,但我在这里看不到它的优势。

最佳答案

My question is how does the compiler here decide what type to use for that array of hex digits?

与数组和聚合类一样,第一个初始化器初始化第一个成员;在这种情况下 i。 (当然,与那些事情不同的是,拥有多个初始化器是没有意义的)。

Why not just store it in the char[4] and skip the union? Is there some advantage of a union here that I don't see?

这样做的目的是初始化 4 字节整数,然后使用 char 数组检查各个字节以确定内存顺序。如果最高有效字节(0x01)存储在第一个字节中,则系统为“big-endian”;否则就是“little-endian”(或者更奇怪的东西)。

关于c++ - 类型双关——编译器如何决定使用什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382926/

相关文章:

c++ - 如何实现关联数组/映射/哈希表数据结构(一般和 C++)

c++ - 为什么这不是一个 constexpr?

c++ - reinterpret_cast 类型双关实际上是未定义的行为吗?

c - 在 C 中通过 union 指针进行类型双关是否合法?

c++ - 使用 std::copy 来解决严格的别名是否安全?

c++ - NSight 分析器使应用程序崩溃

c++ - 如何在 GCC 中弃用 C 预处理器宏?

c++ - 定义模板类、运算符和迭代器的麻烦

c++ - 以 union 作为方法参数

C union 继承