← The C Language Lesson 43 of 77 · 10 XP

Unions: union

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A union looks like a struct, but all its fields lie in the same place in memory. Only one of them is meaningful at a time, and the size of a union equals the size of its largest field:

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

union value v;
v.i = 42;          // now the field i is "alive"
v.f = 3.14f;       // we overwrote the same bytes — i is now meaningless
printf("%zu\n", sizeof(union value));   // 4, not 9

What's it for? To save memory when a value can be one of several types. Usually a "tag" is stored next to it — which type is inside right now:

struct token {
    int kind;          // 0 — a number, 1 — a symbol
    union {
        int number;
        char symbol;
    } as;
};

This is how values are built in language interpreters (including inside CPython), network packets and events in games.

Task. Read tokens until the end of the input: a number or a single operation character. Store each one in a struct token, then print them: numbers as NUM 5, symbols as OP +.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.