Learn C++ - C++ Unions






A union is a data format that can hold different data types but only one type at a time.

A union can hold an int or a long or a double.

The syntax is like that for a structure.

For example, consider the following declaration:

union my_union 
{ 
     int int_val; 
     long long_val; 
     double double_val; 
}; 

You can use a my_union variable to hold an int, a long, or a double,just as long as you do so at different times:

my_union y; 
y.int_val = 15;        // store an int 
cout << y.int_val; 
y.double_val = 1.8;   // store a double, int value is lost 
cout << y.double_val;