为什么我的工会没有显示正确的值?
union
{ int i;
bool b;
} x;
x.i = 20000;
x.b = true;
cout << x.i;
它打印出 19969。为什么它不打印出 20000?
union
{ int i;
bool b;
} x;
x.i = 20000;
x.b = true;
cout << x.i;
It prints out 19969. Why does it not print out 20000?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
union
不是struct
。在联合
中,所有数据占用相同的空间,并且可以通过其字段名称被视为不同的类型。当您将true
分配给xb
时,您将覆盖20000
的低位。更具体地说:
20000 二进制:100111000100000
19969 二进制:100111000000001
这里发生的情况是,您将一个单字节值 1 (00000001) 放入 200000 的 8 个低位中。
如果您使用
struct 而不是
union
,您将有空间容纳int
和bool
,而不仅仅是int
code>,您将看到您期望的结果。A
union
is not astruct
. In aunion
, all of the data occupies the same space and can be treated as different types via its field names. When you assigntrue
tox.b
, you are overwriting the lower-order bits of20000
.More specifically:
20000 in binary: 100111000100000
19969 in binary: 100111000000001
What happened here was that you put a one-byte value of 1 (00000001) in the 8 lower-order bits of 200000.
If you use a
struct
instead of aunion
, you will have space for both anint
and abool
, rather than just anint
, and you will see the results you expected.在联合中,所有数据成员都从同一内存位置开始。在您的示例中,您一次只能真正使用一个数据成员。然而,此功能可用于一些巧妙的技巧,例如以多种方式公开相同的数据:
这允许您通过名称(x、y 和 z)或作为数组(v)访问三个整数。
In a union, all data members start at the same memory location. In your example you can only really use one data member at a time. This feature can be used for some neat tricks however, such as exposing the same data in multiple ways:
Which allows you to access the three integers either by name (x, y and z) or as an array (v).
联合在任何给定时间仅存储一个成员。要获得已定义的结果,您只能从联合体中读取上次写入联合体的相同成员。否则(就像你在这里一样)官方给出的结果只不过是未定义的结果。
有时联合体被有意用于类型双关(例如,查看组成浮点数的字节)。在这种情况下,您需要理解您所得到的内容。该语言有点试图给你一个战斗的机会,但它并不能真正保证太多。
A union only stores one of the members at any given time. To get defined results, you can only read the same member from the union that was last written to the union. Doing otherwise (as you are here) officially gives nothing more or less than undefined results.
Sometimes unions are intentionally used for type-punning (e.g., looking at the bytes that make up a float). In this case, it's up to you to make sense of what you get. The language sort of tries to give you a fighting chance, but it can't really guarantee much.
C 中的 Union 有助于不同变量共享内存空间。
因此,当您更改联合内的任何变量时,所有其他变量的值也会受到影响。
Union in C facilitate sharing of memory space by different variable.
So when you are changing any variable inside union, all other variable's values are also got affected.