我正在阅读 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_t
或 char[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/