Next: Coercion or Type-Casting Up: Further Data Types Previous: Defining New Data Types


A union is a variable which may hold (at different times) objects of different sizes and types. C uses the union statement to create unions, for example:

defines a union called number and an instance of it called anumber. number is a union tag and acts in the same way as a tag for a structure.

Members can be accessed in the following way:

This clearly displays the value of longnumber.

When the C compiler is allocating memory for unions it will always reserve enough room for the largest member (in the above example this is 8 bytes for the double).

In order that the program can keep track of the type of union variable being used at a given time it is common to have a structure (with union embedded in it) and a variable which flags the union type:

An example is:

This example defines a base union aircraft which may either be jet, helicopter, or cargoplane.

In the an_aircraft structure there is a kind member which indicates which structure is being held at the time.
Wed Sep 14 10:06:31 BST 1994