O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The union Keyword

The union keyword is similar to the struct keyword in its notation. For example, the typedef variant takes the following form:

typedef union
{
    <type> <name> ...
} <union_id>;

Although there may be many <type> <name> data members, recall that they all occupy the same space in memory. This is both helpful and confusing. It’s helpful because it enables you to change one item and have that change reflected through the other items. It’s confusing because it is often difficult to tell from the use of the union that it is not a struct, because the data access method is so similar.

A concrete example should help to clarify the meaning of this. Assume that you want to define a union to represent a data type that can be accessed as a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required