Union in C Programming

Union in C programming language is similar to structures. Union is a user defined data structure which is used to store different data type in same memory location. You can define a union with many members, but at any given instance of time only one member can contain value.

For union variable, the storage space allocated is equal to the storage space needed by the largest data member of the union.

Declaration of Union in C

Keyword union is used to define a union. The syntax to define union is similar to defining a structure in C. The union declaration defines a custom data type, that can store multiple member variables of different data types in same memory location.

A variable of type Employee union can store either a string(name of employee) value , an integer(age of employee)value or a float(salary of employee) value at at time but not more than one member. A union variable will only get enough memory to store the largest member of union.For a variable of union Employee will occupy 32 bytes of memory to store the largest member which is name of employee.

Unions efficiently utilize the same memory location for multi-purpose. It occupies less memory because the storage space needed by the union is size of the largest data member.

Disadvantage of Union over Structure

Unions cannot store multiple value at a time.

Difference between Structure and Union

In Structure, all the data members are stored in separate memory locations whereas in Union all members share same memory location.

The memory occupied by a structure variable is equal to sum of the memory of all structure members whereas the memory occupied by a union variable is equal to the storage space needed by the largest data member of the union.

At a time, a union variable can contain only one active member, whereas a structure variable contains all member.