A union
is a type that enables you to store different data types in the same memory space (but not simultaneously). A typical use is a table designed to hold a mixture of types in some order that is neither regular nor known in advance. By using an array of unions, you can create an array of equal-sized units, each of which can hold a variety of data types.
union
s are set up in much the same way as structures.
Another place you might use a union
is in a structure for which the stored information depends on one of the members. For example, suppose you have a structure representing an automobile. If the automobile is owned by the user, you want a structure member describing the owner. If the automobile is leased, you want the member to describe the leasing company. Then you can do something along the following lines:
struct owner {
char socsecurity[12];
...
};
struct leasecompany {
char name[40];
char headquarters[40];
...
};
union data {
struct owner owncar;
struct leasecompany leasecar;
};
struct car_data {
char make[15];
int status; /* 0 = owned, 1 = leased */
union data ownerinfo;
...
};
Suppose flit
s is a car_data
structure. Then if flits.status
were 0
, the program could use flits.ownerinfo.owncar.socsecurity
, and if flits.status
were 1
, the program could use
flits.ownerinfo.leasecar.name
.
This is all taken from the book C Primer Plus 5th Edition