LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

What is a union in C and why would you use it?

A union overlays all its members at the same address (size = largest member), so only one member holds a meaningful value at a time — handy for saving space or reinterpreting bits.

Union members overlap at offset 0

* A union lays every member at offset 0, so they share the same storage; its size is that of the largest member. *

union flint {
    int i;
    float f;
// Size = max(sizeof(int), sizeof(float))
};

All members share the same address:

union flint x;
x.f = 3.14;
// Print float's bit pattern as int!
printf("%08x\n", x.i);

Use case 1: Type punning (view same bits differently)

void print_float_hex(float f) {
    union {
        int i;
        float f;
    } u;
    u.f = f;
    printf("%08x\n", u.i);
}

Use case 2: Memory-efficient variants

struct packet {
    int type;
    union {
        struct { int x, y; } position;
        struct { char msg[100]; } message;
        struct { float value; } sensor;
    } data;
// data is only as big as the largest member
};

Warning: Reading a different member than you wrote is technically undefined behavior (but widely used for type punning).

Go deeper:

From Quiz: REVE1 / C Programming | Updated: Jul 10, 2026