Unions in C Programming (Complete Guide with Examples)


This tutorial explains unions in C, which are similar to structures but store only one member at a time in the same memory location. It covers declaration, initialization, memory efficiency, and practical examples for beginners.

1. What is a Union

  1. A union is a user-defined data type similar to a structure.
  2. All members share the same memory location, so only one member can store a value at a time.
  3. Useful for memory-efficient storage when only one of the members is needed at a time.

2. Syntax


union union_name {
data_type member1;
data_type member2;
...
};

3. Example: Basic Union


#include <stdio.h>

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

int main() {
union Data data;

data.i = 10;
printf("data.i = %d\n", data.i);

data.f = 220.5;
printf("data.f = %.2f\n", data.f);

strcpy(data.str, "Muni");
printf("data.str = %s\n", data.str);

// Only the last assignment is valid
printf("data.i after assigning str = %d\n", data.i);

return 0;
}

Sample Output:


data.i = 10
data.f = 220.50
data.str = Muni
data.i after assigning str = 0 // value overwritten

Explanation:

  1. All members share the same memory
  2. Assigning a value to one member overwrites the previous value

4. Key Points to Remember

  1. Union members share memory, unlike structures where each member has its own memory
  2. Only one member can hold a value at a time
  3. Saves memory in applications where not all members are used simultaneously
  4. Can be combined with structures, arrays, and pointers for complex applications