Skip to content
AgileLogics
3 min read

Unions

Prerequisites: Memory leaks & common pitfalls

A union looks like a struct but its members share the same memory — it's exactly big enough for its largest member, and writing one member overwrites whatever was in the others.

union Value {
    int i;
    float f;
    char c;
};

union Value v;
v.i = 65;
printf("%d\n", v.i);   // 65
printf("%c\n", v.c);   // 'A' — same memory, read as a char

Unions are used sparingly in modern C — mainly for representing "one of several possible types" compactly, often paired with a separate field recording which member is currently valid.