Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my union not show the correct values?

Tags:

c

unions

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?

like image 283
Joe Avatar asked May 19 '10 19:05

Joe


People also ask

How do you assign a value to a union?

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.

What is union in c?

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.


2 Answers

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.

like image 79
danben Avatar answered Oct 22 '22 17:10

danben


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

like image 34
Niki Yoshiuchi Avatar answered Oct 22 '22 16:10

Niki Yoshiuchi