Back to course

Unions and their Use Cases

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 45: Unions and their Use Cases

A Union is similar to a structure, but with a critical difference: all members of a union share the same memory location.

Defining and Using a Union

Rule: The size of a union is equal to the size of its largest member.

c union Data { int i; float f; char str[20]; };

int main() { union Data data;

// The memory is large enough for the largest member (str, 20 bytes).
printf("Memory size occupied by Data: %zu\n", sizeof(data)); // Output: ~20

// 1. Assign value to 'i'
data.i = 10; 
printf("data.i : %d\n", data.i); 

// 2. Assign value to 'f' (this overwrites the memory where 'i' was stored)
data.f = 220.5;
printf("data.f : %f\n", data.f); 

// 3. Trying to read 'i' now gives garbage (memory overwritten)
printf("data.i (after f update): %d\n", data.i); 

return 0;

}

Use Cases

  1. Memory Optimization: Unions are used when you know that only one of the members will be used at any given time, saving memory.
  2. Type Punning: Used in low-level programming to interpret the same block of memory in different ways (e.g., reading an integer as a sequence of characters).