Summary: A union is a group of variables of different types that share storage space.
A union is a variable that can hold any one of several data types at different times, using the same storage space. Unions are a rather advanced feature. One use of them is to access DOS registers, which you may sometimes need to access as bytes and at other times as words.
As with a structure, you must start by declaring a union type to tell the compiler the number and types of the union's members. You include one of each type that you expect to use.
The following code creates a union that can hold a char, int, or long value. It declares a union type with the tag u_sample and declares a variable of that type named example.
union u_sample
{
char c_val;
int i_val;
long l_val;
} example;
When you declare a union, QuickC allocates as much storage as the largest data type in the union requires. Since the largest type in u_sample is long, this union contains four bytes.
The elements of a union are called members and use the same notation as structure members. Thus, the members of the example union are named
example.c_val
example.i_val
example.l_val
The contents of a union depend on how you access it. For instance, the statement
example.c_val = '\0';
stores a char value in the example union. Since a char value takes one byte, the statement uses only one byte of the space in example. The statement
example.i_val = 77;
uses two bytes of the union, because an int value requires two bytes of storage. Likewise, the statement
example.l_val = 75621;
stores long value in example, taking up all four bytes of its storage space. Figure 4.11 shows memory allocation for the three members in the example union.
It's your job to keep track of what is stored in a union. If you store a long value in example and mistakenly treat that value as a char value later, the result may be nonsense. It's especially important not to confuse integer and floating-point types, which are stored in different internal formats.
Now that you're familiar with the data types that C offers, you are ready to tackle more advanced data-handling concepts. The next chapter discusses several of these.