田间结合与结构结合之间的差异

difference between union of fields and union of structures

本文关键字:结合 结构 田间 之间      更新时间:2023-10-16

我正在定义一组结构来处理某些寄存器,当我定义结构时,我发现定义简单字段的结合和结构结合之间。我不确定为什么会发生这种差异:

#include <iostream>
using namespace std;

typedef union
{
    uint16_t all_bits;
    struct
    {   
        uint16_t a:4, b:4, c:4, d:3, e:1;
    };  
}
Example1_t;
typedef union
{
    uint16_t all_bits;
    uint16_t a:4, b:4, c:4, d:3, e:1;
}
Example2_t;
    int 
main ()
{
    Example1_t example1;
    Example2_t example2;
    example1.all_bits = 0x8BCD;
    example2.all_bits = 0x8BCD;
    cout << "a " << std::hex << example1.a << " " << example2.a << std::endl;
    cout << "b " << std::hex << example1.b << " " << example2.b << std::endl;
    cout << "c " << std::hex << example1.c << " " << example2.c << std::endl;
    cout << "d " << std::hex << example1.d << " " << example2.d << std::endl;
    cout << "e " << std::hex << example1.e << " " << example2.e << std::endl;
    return 0;
}

输出:

a d d                                                                                                                                        
b c d                                                                                                                                        
c b d                                                                                                                                        
d 0 5                                                                                                                                        
e 1 1   

pedantic答案是:

您的代码具有未定义的行为。写信给联合领域并从另一个领域进行阅读是不保证的,因此您认为的任何矛盾都可以被用作"损坏的代码"。

实际上,,许多野外的人都依赖这种"破碎的行为"是一致的,以至于所有现代编译器仍然在这里提供可预测的功能(以忽略一些优化机会为代价(。因此,您的代码中确实存在某些特定的东西,使其以其方式行事:

Example1_t中,联合有两个重叠字段:all_bits和结构。在该结构内,每个成员都有不同的存储。

Example2_tabcde都是联合的单独字段,因此它们都有重叠的存储空间。