Defining a union
union
s offer a convenient way to represent a set of mutually exclusive values of different types. As an example, we might have a process that handles different kinds of numeric or character data. That process might define a union
to hold these values:
// objects of type Token have a single member, which could be of any of the listed typesunion Token {// members are public by default char cval; int ival; double dval;};
A union
is defined starting with the keyword union
, followed by an (optional) name for the union
and a set of member declarations enclosed in curly braces. This code defines a union
named Token
that can hold a value that is either a char
, an int
, or a double
.
Get C++ Primer, Fifth 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.