typestar

X-macros in C

One list, several expansions: the table and the code stay in step by construction.

#include <stdio.h>

#define STATES(X) \
    X(IDLE) \
    X(RUNNING) \
    X(DONE)

#define AS_ENUM(name) STATE_##name,
#define AS_STRING(name) #name,

typedef enum { STATES(AS_ENUM) STATE_COUNT } State;

static const char *names[] = {STATES(AS_STRING)};

void list_states(void) {
    for (int i = 0; i < STATE_COUNT; i++) {
        printf("%d = %s\n", i, names[i]);
    }
}

How it works

  1. The list is a macro that calls a per-item macro.
  2. Redefining that macro re-uses the list for a new purpose.
  3. Adding an item updates the enum and the names together.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
346
Tokens
77
Three-star pace
100 tpm

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

Type this snippet

Step 3 of 3 in Text manipulation, step 7 of 12 in Preprocessor & headers.

← Previous Next →