其他分享
首页 > 其他分享> > c – 类型惩罚 – 编译器如何决定使用哪种类型?

c – 类型惩罚 – 编译器如何决定使用哪种类型?

作者:互联网

我正在阅读this question here about deciding 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]中并跳过联合?

在这里,我看不到一个工会的优势吗?我知道这被称为打字,但我没有看到它的优势.

解决方法:

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

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

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”;否则它是“小端”(或者可能是一些陌生人).

标签:c,unions,type-punning
来源: https://codeday.me/bug/20190725/1533363.html