BCA / B.Tech 12 min read

Unions in C

Union in the C Language:


In the C programming language, a union is a user-defined data type that works similarly to a struct, but with one important difference. A union is used when we want to store different types of data in the same memory location. Through a union, we can share a single memory block for different types of data, which leads to efficient use of memory.

Definition of Union:
A union is a data type that has the capacity to store one or more members, but all members use the same memory location. This means that at any given time, a union can hold a value for only one member, because all members share the same memory space.

Syntax and Example:
A union is declared using the `union` keyword, similar to a struct. The provided example demonstrates a `Data` union with `int`, `float`, and `char` array members. It shows that when a value is assigned to one member, the values of the other members become corrupted because they all share the same memory.

Key Points of Working with Unions:
  • Only One Member at a Time: Only one member of a union can be correctly accessed at any given time.
  • Memory Space: The total size of a union is equal to the size of its largest member.
  • Memory Saving: The primary use of a union is to save memory.

Where are Unions Used?
Unions are mainly used when memory needs to be used efficiently, such as in embedded systems, managing sensitive data of different formats, data packing in network programming or hardware interfacing.