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?
In union at a time you can assign one value. In union the values are overlapped with each other. So you are doing the wrong with assigning values to two elements of union. It will always show the last assigned value.
Union in C is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With