typestar

A tagged union in C

The C way to write a sum type: an enum saying which member is live.

typedef enum { VALUE_INT, VALUE_DOUBLE, VALUE_TEXT } Kind;

typedef struct {
    Kind kind;
    union {
        long as_int;
        double as_double;
        const char *as_text;
    } data;
} Value;

double as_number(const Value *v) {
    switch (v->kind) {
    case VALUE_INT:
        return (double) v->data.as_int;
    case VALUE_DOUBLE:
        return v->data.as_double;
    case VALUE_TEXT:
    default:
        return 0.0;
    }
}

How it works

  1. The tag and the union travel together in one struct.
  2. A switch on the tag is the only safe way to read it.
  3. This is how interpreters represent values.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
354
Tokens
88
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 2 of 5 in Unions & layout, step 2 of 13 in Unions, bitfields & undefined behavior.

← Previous Next →