Unions allow two ALTERNATIVE data items to share storage.
union number { int i; float f; } x;
x can now be either an integer, or a float. Use
... x.i /* the integer */ ... x.f /* the float */
Beware of assigning to `x.i' and then using the value of `x.f'. There are no machine checks.
You may typically have a marker to tell you the type of object currently stored.
struct header { int type; ... various other fields ... union { struct { ... this lot ... } s1; struct { ... that lot ... } s2; } un; } hd;
The `type' field keeps an indicator of the type of structure stored.
switch( hd.type ) { case 1: hd.un.s1.s1field = ...; break; case 2: hd.un.s2.s2field = ...; break; default: ... error ... }
This will be familiar to Pascal freaks.
enum { spade, heart, club, dia } suit; suit = heart; if ( suit == club ) { ... }
enum suitype { spade, ht, club, dia }; enum suitype suit; suit = (enum suitype) 2; /* club? */
Copyright Eric Foxley 1996
Notes converted from troff to HTML by an Eric Foxley shell script, email errors to me!