C Reference ยท Preprocessor
X macros
Reference for the C X macro technique: define a list once and expand it into enums, name tables, switch cases and structs, keeping them in sync.
An X macro is a pattern, not a language feature. You write a list of items once as a macro that calls another macro (traditionally named X) for each entry. Then you define X differently each time you expand the list, so the same data produces an enum, a table of names, a switch, or a struct, and all of them stay in sync automatically.
It solves a classic problem: an enum and an array of its names, kept in two places, drift apart the moment someone adds a value to one and forgets the other.
#define COLORS(X) \ X(RED, "red") \ X(GREEN, "green") \ X(BLUE, "blue")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
How it works
- The list macro takes one parameter, the name of another macro, and calls it once per entry:
COLORS(X). Each entry can carry several values (an identifier, a string, a number). - Each expansion defines a small macro with the same number of parameters, expands the list through it, and (optionally)
#undefs it afterwards. - The pieces you generate (enumerator lists, initializers,
caselabels, struct members) need the separators in different places. Comma-terminated entries work for enums and initializers because C allows a trailing comma. For other contexts, put the separator into the per-item macro (case ...: ...;) rather than into the list.
Passing the macro as an argument
The list is written as COLORS(AS_ENUM): the name AS_ENUM is substituted for X and the result is rescanned, which expands each X(...) into a use of AS_ENUM(...). This relies on rescanning (see #define). The older style defines a global X, includes or expands a list that mentions it, then #undef X; the parameterized style above is easier to read and cannot leak a stray X into later code.
Usage notes
- Adding an entry is a one-line change. Every generated construct updates itself, which is the whole point.
- Use designated initializers (
[COLOR_RED] = "red") in generated tables so the order of the list does not have to match the order of the enum. - Entries must be preprocessor tokens. Commas inside an entry's value need parentheses, and an entry cannot contain
#iflines, since directives are not allowed inside macro arguments. - Error messages point at the macro. A mistake in one entry is reported at the line where the list is expanded, so keep entries simple.
- Keep the list near the top of its header and give the helper macros descriptive names (
AS_ENUM,AS_NAME). - Alternatives. A plain array of structs (
static const struct { enum Color id; const char *name; } table[] = {...}) is more debuggable when the data is only needed at run time. X macros earn their keep when the types (enum, struct members,caselabels) must be generated too. A list can also live in its own file that is#included repeatedly with different definitions ofX. - Sentinel. A final
COLOR_COUNTafter the generated enumerators gives you the array size and a loop bound.
Related
#define, The#operator, The##operator,enum, Macro pitfalls- Lessons: Macros, Enums