Skip to content
  • Unions · C

Unions

LearnViaNotes @learnvianotes· 2 min read

A union is like a struct whose members all share the same memory. It is as large as its largest member, and only one member holds a meaningful value at a time.

C
#include <stdio.h>

union Value {
    int i;
    float f;
    char bytes[8];
};

int main(void) {
    union Value v;
    printf("sizeof = %zu\n", sizeof v);      /* the largest member */
    v.i = 65;
    printf("i = %d\n", v.i);
    v.f = 2.5f;                               /* overwrites the same bytes */
    printf("f = %.1f\n", v.f);
    printf("same address: %d\n", (void *)&v.i == (void *)&v.f);
    return 0;
}
Output
sizeof = 8
i = 65
f = 2.5
same address: 1

Tagged unions (sum types)

Pair a union with an enum tag recording which member is active — the C equivalent of a variant or enum in Rust:

C
#include <stdio.h>

typedef enum { SHAPE_CIRCLE, SHAPE_RECT } ShapeKind;

typedef struct {
    ShapeKind kind;                 /* the tag */
    union {                         /* anonymous union (C11) */
        struct { double r; } circle;
        struct { double w, h; } rect;
    };
} Shape;

double area(const Shape *s) {
    switch (s->kind) {
        case SHAPE_CIRCLE: return 3.14159 * s->circle.r * s->circle.r;
        case SHAPE_RECT:   return s->rect.w * s->rect.h;
    }
    return 0;
}

int main(void) {
    Shape shapes[] = {
        {.kind = SHAPE_CIRCLE, .circle = {1.0}},
        {.kind = SHAPE_RECT, .rect = {3, 4}},
    };
    for (int i = 0; i < 2; i++) printf("area = %.2f\n", area(&shapes[i]));
    printf("sizeof(Shape) = %zu\n", sizeof(Shape));
    return 0;
}
Output
area = 3.14
area = 12.00
sizeof(Shape) = 24

Inspecting bytes and endianness

C
#include <stdio.h>
#include <stdint.h>

int main(void) {
    union { uint32_t word; uint8_t b[4]; } u = {.word = 0x11223344};
    printf("%02X %02X %02X %02X\n", u.b[0], u.b[1], u.b[2], u.b[3]);
    printf("%s-endian\n", u.b[0] == 0x44 ? "little" : "big");
    return 0;
}
Output
44 33 22 11
little-endian
structunion
MemoryEach member has its own storageAll members overlap
sizeof≥ sum of members (plus padding)Largest member (plus padding)
Active membersAll at onceOne at a time
UseRecordsVariants, memory saving, byte views

What is the difference between a structure and a union?

How can you check the endianness of a machine?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report