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 types
union 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
.