Skip to content

C Unions

Unions are special data types that allow storing different data types in the same memory location.

1. Union Definition

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

2. Using Unions

c
union Data data;
data.i = 10;
printf("Integer: %d\n", data.i);

data.f = 3.14;
printf("Float: %f\n", data.f);

3. Memory Usage

c
printf("Size of union: %zu\n", sizeof(union Data));
// Size is the size of the largest member

4. Use Cases

  • Type punning
  • Memory optimization
  • Variant data types

Content is for learning and research only.