C Programming Tutorial
Computer Tutorial

Unions



What is Unions

A union is a memory location that is shared by two or more different types of variables. A union provides a way of interpreting the same bit pattern in two or more different ways. Declaring a union is similar to declaring a structure.

Its general form is :

union tag {
type member-name;
type member-name;
type member-name;
.
.
.
} union-variables;

For example:
union u_type {
int i;
char ch;
};

This declaration does not create any variables. You can declare a variable either by placing its name at the end of the declaration or by using a separate declaration statement. To declare a union variable called cnvt of type u_type using the definition just given, write
union u_type cnvt;

In cnvt, both integer i and character ch share the same memory location. Of course, i occupies 2 bytes (assuming 2-byte integers), and ch uses only 1. Figure 7-2 shows how i and ch share the same address. At any point in your program, you can refer to the data stored in a cnvt as either an integer or a character.

Union in memory

Union in memory

When a union variable is declared, the compiler automatically allocates enough storage to hold the largest member of the union. For example, (assuming 2-byte integers) cnvt is 2 bytes long so that I can hold i, even though ch requires only 1 byte.

To access a member of a union, use the same syntax that you would use for structures: the dot and arrow operators. If you are operating on the union directly, use the dot operator. If the union is accessed through a pointer, use the arrow operator. For example, to assign the integer 10 to element i of cnvt :
cnvt.i = 10;