Unions

Contents

Unions#

A union overlays multiple fields in the same memory. Only one field is meaningful at a time; the operator tracks which one with a sibling tag.

struct value {
    enum { V_INT, V_STR } kind;
    union {
        int         i;
        const char *s;
    } as;
};

Reading a different field from the one last written is implementation-defined. The “tag plus union” pattern keeps the invariant explicit.

References#

  • Structs for the typed-record sibling.

  • Enums for the typical tag type.