C Unions

A union looks a lot like a structure, but with one big difference: all of its members share the same block of memory. That means a union can hold only one of its members at any given time. Unions are used when you want a single variable to store different kinds of data at different moments, while saving memory.

How a union differs from a struct

In a struct, every member gets its own space, so the total size is the sum of all members. In a union, the members overlap, so the total size is just big enough for the largest member. Writing to one member overwrites the others.

Defining and using a union

#include <stdio.h>

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

int main() {
    union Value v;

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

    v.f = 3.14f;   // overwrites the same memory
    printf("As float: %.2f\n", v.f);
    return 0;
}

After v.f = 3.14f, reading v.i would give a meaningless number, because the bits now represent a float. You should only read the member you most recently wrote.

Union size

Because all members share storage, the size of a union equals the size of its largest member (possibly rounded up for alignment). You can confirm this with the sizeof operator.

Checking the size of a union

#include <stdio.h>

union Mixed {
    char letter;    // 1 byte
    int number;     // 4 bytes
    double amount;  // 8 bytes
};

int main() {
    printf("Size of union: %lu bytes\n", sizeof(union Mixed));
    return 0;
}
Featurestructunion
Memory for membersSeparate for eachShared by all
Total sizeSum of membersSize of largest member
Members usable at onceAllOnly one
Keywordstructunion
Note: Reading a union member other than the one you last wrote gives unpredictable results. A common safe pattern is to keep a separate variable that records which member is currently valid.