Total Pageviews

Friday, 4 May 2012

Unions

Unions
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:
                 union number
                             {
                             short shortnumber;
                             long longnumber;
                             double floatnumber;
                             } anumber
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:

          printf("%ld\n",anumber.longnumber);

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:

              typedef struct
                             { int maxpassengers;
                             } jet;

              typedef struct
                             { int liftcapacity;
                             } helicopter;

              typedef struct
                             { int maxpayload;
                             } cargoplane;

               typedef union
                             { jet jetu;
                               helicopter helicopteru;
                               cargoplane cargoplaneu;
                             } aircraft;

              typedef  struct
                             { aircrafttype kind;
                               int speed;
                               aircraft description;
                             } an_aircraft;

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. 

No comments:

Post a Comment