San*_*Fry 1 c++ struct unions bit-fields
我正在定义一组结构来处理一些寄存器,当我定义结构时,我发现定义简单字段的联合和结构的联合之间存在差异。我不确定为什么会出现这种差异:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
a d d
b c d
c b d
d 0 5
e 1 1
Run Code Online (Sandbox Code Playgroud)
小智 5
迂腐的答案是:
您的代码具有未定义的行为。写入联合字段并从另一个字段读取并不能保证有效,因此您看到的任何不一致都可以作为“损坏的代码”而被忽略。
事实上,很多人都依赖这种“破坏行为”的一致性,以至于所有现代编译器仍然在这里提供可预测的功能(以忽略一些优化机会为代价)。因此,您的代码中确实有一些特定的东西使它的行为方式如下:
在 中Example1_t,联合有两个重叠的字段:all_bits和 struct。在该结构中,每个成员都有不同的存储空间。
在Example2_t、a、b、c和d中e都是并集的独立字段,因此它们都有重叠的存储。