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