union Keyword

Keyword Index

Groups variables which share the same storage space.

A union is similar to a struct, except it allows you to define variables that share storage space. The syntax for defining unions is:

union [union-type-name]
  {
    type variable-names;
    ...
  } [union-variables] ;
For example,
union short_or_long
  {
    short i;
    long l;
  } a_number;
The compiler will allocate enough storage in a number to accommodate the largest element in the union. Elements of a union are accessed in the same manner as a struct.

Unlike a struct, the variables 'a_number.i' and 'a_number.l' occupy the same location in memory. Thus, writing into one will overwrite the other.