Union in C

A union is a user-defined data type in C that allows storing different data types in the **same memory location**.

Unlike structures (where each member gets its own separate memory), in a union **only one member can be used at a time**, and the size of the union is equal to the size of its **largest member**.

Memory efficient – saves space
All members share the same memory address
Only one member is 'active' at a time
Very useful for type punning and memory reinterpretation

1. Declaration and Syntax

C
Basic union declaration
union Data {
    int i;         // 4 bytes
    float f;       // 4 bytes
    char c;        // 1 byte
    double d;      // 8 bytes (largest)
};

// Size of union Data = 8 bytes (size of double)
Note: Size of union = size of its largest member (including any padding)

2. Simple Example – Memory Sharing

C
Demonstrating shared memory
#include <stdio.h>

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

int main() {
    union Data d;

    d.i = 65;
    printf("As int: %d\n", d.i);           // 65

    printf("As float: %f\n", d.f);         // garbage or 0.000000

    d.f = 3.14;
    printf("As float: %f\n", d.f);         // 3.140000
    printf("As int now: %d\n", d.i);       // some integer representation of 3.14

    strcpy(d.str, "Hello Union");
    printf("As string: %s\n", d.str);      // Hello Union

    printf("Size of union: %zu bytes\n", sizeof(d));  // 20 bytes

    return 0;
}

3. Union vs Structure – Comparison

FeatureStructureUnion
Keywordstructunion
Memory AllocationSeparate for each memberShared (same location)
SizeSum of all members + paddingSize of largest member
All members active?YesNo – only one at a time
Use CaseGroup different related dataMemory saving, type punning, variant types
Typical Size Examplechar + int + float → ~12 byteschar + int + float → 4 bytes

4. Common Real-World Use Cases of Union

  • Variant types / Tagged unions (store different types with a type tag)
  • Type punning (reinterpret memory)
  • Parsing network packets / binary file formats
  • Hardware register access (different views of same bits)
  • Saving memory in embedded systems
  • Low-level programming (overlapping fields)
C
Tagged Union (Variant) example
enum Type { INT, FLOAT, STRING };

struct Variant {
    enum Type type;
    union {
        int i;
        float f;
        char str[32];
    } value;
};

5. Common Pitfalls & Best Practices

  • Don't read a member after writing to another (undefined behavior in some cases)
  • Use tagged unions to safely track active member
  • Be careful with type punning (strict aliasing rule in C)
  • Union with arrays/strings needs careful handling
  • Padding may still exist inside union members