

union                       C Keyword                       union




Multiply declare a variable


A union  defines an area  of storage that  can accept any  one of
several types  of data.  In effect, it  is a multiple declaration
of a  variable.  For example, a union may  be declared to consist
of  an int,  a double,  and  a char  *.  Any  one of  these three
elements can be held by the  union at a time, and will be handled
appropriately by it.  For example, the declaration


union {
        int number;
        double bignumber;
        char *stringptr;
} example;


allows example to hold either an iinntt, a ddoouubbllee, or a pointer to a
cchhaarr, whichever  is needed  at the time.   All of these  have the
same address.  The elements of a uunniioonn are accessed like those of
a ssttrruucctt:  for example, to access nnuummbbeerr  from the above example,
type eexxaammppllee.nnuummbbeerr.

unions are helpful in dealing with heterogeneous data, especially
within structures; however, you are responsible for keeping track
of what data  type the union is holding at  any given time.  Pas-
sing a double to a union  and then reading the union as though it
held  an  int  will yield  results  that  are unpredictable,  and
probably unwelcome.

***** Example *****

For an example of how to  use a union in a program, see the entry
for byte ordering.

***** See Also *****

C keywords, struct, structure

















COHERENT Lexicon                                           Page 1


