为什么我的工会没有显示正确的值?

发布于 2024-09-02 01:14:39 字数 134 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

云朵有点甜 2024-09-09 01:14:39

union 不是 struct。在联合中,所有数据占用相同的空间,并且可以通过其字段名称被视为不同的类型。当您将 true 分配给 xb 时,您将覆盖 20000 的低位。

更具体地说:

20000 二进制:100111000100000

19969 二进制:100111000000001

这里发生的情况是,您将一个单字节值 1 (00000001) 放入 200000 的 8 个低位中。

如果您使用 struct 而不是 union,您将有空间容纳 intbool,而不仅仅是 int code>,您将看到您期望的结果。

A union is not a struct. In a union, all of the data occupies the same space and can be treated as different types via its field names. When you assign true to x.b, you are overwriting the lower-order bits of 20000.

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 a union, you will have space for both an int and a bool, rather than just an int, and you will see the results you expected.

锦上情书 2024-09-09 01:14:39

在联合中,所有数据成员都从同一内存位置开始。在您的示例中,您一次只能真正使用一个数据成员。然而,此功能可用于一些巧妙的技巧,例如以多种方式公开相同的数据:

union Vector3
{
  int v[3];
  struct
  {
    int x, y, z;
  };
};

这允许您通过名称(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:

union Vector3
{
  int v[3];
  struct
  {
    int x, y, z;
  };
};

Which allows you to access the three integers either by name (x, y and z) or as an array (v).

热血少△年 2024-09-09 01:14:39

联合在任何给定时间仅存储一个成员。要获得已定义的结果,您只能从联合体中读取上次写入联合体的相同成员。否则(就像你在这里一样)官方给出的结果只不过是未定义的结果。

有时联合体被有意用于类型双关(例如,查看组成浮点数的字节)。在这种情况下,您需要理解您所得到的内容。该语言有点试图给你一个战斗的机会,但它并不能真正保证太多。

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.

⒈起吃苦の倖褔 2024-09-09 01:14:39

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文