Unions

A union is a data format that can hold different data types but only one type at a time. That is, whereas a structure can hold, say, an int and a long and a double, a union can hold an int or a long or a double. The syntax is like that for a structure, but the meaning is different. For example, consider the following declaration:

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

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

one4all pail;
pail.int_val = 15;          // store an int
cout << pail.int_val;
pail.double_val = 1.38;     // store a double, int value is lost
cout << pail.double_val;

Thus, pail can serve as an int variable on one occasion and as a double ...

Get The Waite Group's C++ Primer Plus, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.