Union types

A union allows a data type to be defined where all or part of the contents have more than one layout, depending on use. A simple example is:
    union int_or_double {
        int ival;
        double dval;
    };
A variable of this type, such as:
    union int_or_double iod;
has the size of the larger of the elements, ival or dval. These elements are regarded as alternative ways of using the space of the union, rather than as separate co-existing items, as in structs. Thus, a value being stored in iod by using iod.ival is treated as an integer assignment. If the same value is retrieved using iod.dval it is assumed to be a double and the same pattern of bits will be interpreted differently.

This is not particularly useful. It is in fact potentially unsafe to rely on this sort of thing. The real use of unions is to allow records with different internal structures to be stored in the same array or other data structure. This would typically involve defining several structs with a common prefix and building a union based on them. Such a union is equivalent to a variant record in Pascal or Ada.

    struct engine {
        char * name;
        char * maker;
        int capacity;
    };

struct seats {
        char * name;
        char * maker;
        char * style;
    };

struct radio {
        char * name;
        char * maker;
        int min_freq;
        int max_freq;
    };

union car_part {
        struct engine ept;
        struct seats spt;
        struct radio rpt;
    };
The union car_part is not the best way to structure these variations, since it requires you to type cp.ept.name or cp.spt.name or cp.rpt.name in order to access the name field, which exists in all three variations. It would be more elegant to define car_part as a struct, with its last element as a union of those fields which are different in the specific types of part. Thus, we could have written:
struct radio {
        int min_freq;
        int max_freq;
    };

struct car_part {
      char * name;
      char * maker:
      union {
         int capacity;
         char * style:
         struct radio rpt;
      }
};

Exercises on this section.


Next - Typedef again.

Back to Contents page.