Why does my union not show the correct values?

2019-04-19 07:36发布

问题:

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?

回答1:

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.



回答2:

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).



回答3:

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.



回答4:

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.



标签: c unions