What Is Union in Data Structure?

//

Larry Thompson

What Is Union in Data Structure?

In data structures, a union is a user-defined data type that allows storing different types of data in the same memory location. It is similar to a structure, but with one key difference – a union can only hold one value at a time.

Declaring and Using Unions

To declare a union in C or C++, you use the union keyword followed by the union name. Inside the union, you define member variables of different types. Here’s an example:

<!-- Code Example -->
union MyUnion {
    int i;
    float f;
    char c;
};

In this example, we have declared a union called MyUnion. It has three member variables - an integer i, a float f, and a character c.

You can then create variables of this union type and access its members:

<!-- Code Example -->
union MyUnion myVar;
myVar.i = 10;       // assigning value to i
printf("%d", myVar.i);  // accessing i

myVar.f = 3.14;     // assigning value to f
printf("%f", myVar.f);  // accessing f

myVar.c = 'A';      // assigning value to c
printf("%c", myVar.c);  // accessing c

In this code snippet, we create an instance of MyUnion called myVar. We can assign values and access members of the union using the dot operator.

Memory Allocation

One of the key aspects of unions is that they share memory space among their members. The size of a union is determined by its largest member. For example, if a union has a member variable of type int (4 bytes), and another member variable of type char (1 byte), the size of the union will be 4 bytes.

This shared memory allocation means that changing the value of one member will affect the values of other members. Only the last assigned value is retained in the union's memory.

Use Cases for Unions

Unions are particularly useful when you need to store different types of data in a limited amount of memory. They can be handy in scenarios such as:

  • Data Type Conversion: Unions allow you to efficiently convert between different data types without needing additional memory.
  • Data Compression: Unions can be used to compress multiple data types into a single entity, saving memory space.
  • Parsing Data: When reading binary data, unions can help interpret different parts of the binary stream as different data types.

Summary

In summary, a union is a user-defined data type that allows storing different types of data in the same memory location. It provides an efficient way to save memory by sharing space among its members. Unions are commonly used for type conversion, data compression, and parsing binary data.