首页 > 解决方案 > 字段联合和结构联合之间的区别

问题描述

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

#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;
}

输出:

添加
bcd
cbd
d 0 5
e 1 1

标签: c++structunionbit-fields

解决方案


迂腐的答案是:

您的代码具有未定义的行为。写入联合字段并从另一个字段读取并不能保证有效,因此您看到的任何不一致都可以作为“损坏的代码”手动消除。

实际上,很多人都依赖于这种“破坏行为”的一致性,以至于所有现代编译器仍然在这里提供可预测的功能(以忽略一些优化机会为代价)。因此,您的代码中确实有一些特定的东西使它的行为方式如下:

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

Example2_t, a, b, c,de都是并集的独立字段,所以它们都有重叠存储。


推荐阅读