It's good if you have a variable which can be either a char
, or a int
, or ...
It's often used inside structures that contain the actual type of the union. Often used by parsers to return a token from the lexer. Something like:
struct token
{
int token_type;
union
{
char *s; /* For string or keyword tokens */
double f; /* For floating point tokens */
long i; /* For integer tokens */
} token_value;
};
In the above structure, the used member in the token_value
member depends on the token_type
member.
Unions can also be used by misusing the data in the union, where you set one member of the variable and read another. This can, for example, be used to convert a floating point number to a series of bytes.
Like
union data
{
char data[sizeof(double)];
double value;
};
By setting the value
member, you can read the separate bytes of the double
value without typecasting or pointer arithmetic. This is technically implementation defined behavior, which means that a compiler may not allow it. It is very commonly used though, so all current compilers allow it.