Union

1

Enums and Unions

5 minute

In C, enum and union often appear together. The enum says which kind of value is active, and the union reuses the same storage for different payloads:

enum ValueKind {
    VALUE_INT,
    VALUE_FLOAT,
    VALUE_TEXT,
};

struct Value {
    enum ValueKind kind;
    union {
        int i;
        float f;
        const char *text;
    } data;
};

This is a tagged union. It is common and useful, but correctness depends on discipline:

if (value->kind == VALUE_INT) {
    printf("%d\n", value->data.i);
}

If kind is VALUE_TEXT and the code reads data.i, the C type system does not stop it. In Rust, this shape is usually represented with enum, where the tag and the data live in one type.

Read More