田间结合与结构结合之间的差异
difference between union of fields and union of structures
我正在定义一组结构来处理某些寄存器,当我定义结构时,我发现定义简单字段的结合和结构结合之间。我不确定为什么会发生这种差异:
#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_t
,a
,b
,c
,d
和e
都是联合的单独字段,因此它们都有重叠的存储空间。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 多态性和功能结合
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 与现有VAR无法实现结构化结合
- 结构化结合和绑带()
- 可能是嵌套结构化结合物
- 田间结合与结构结合之间的差异
- 模板结构结合枚举
- 具有结构化结合的不同CV质量剂
- 结构绑定:与公共数据成员(继承的基类)结合
- 将'std::cin'与数据结构成员结合使用
- 将 STL 队列与自定义数据结构结合使用