Enum and name table
An enum and its string table generated from one list, so they cannot drift apart.
+ <stdio.h>
# Enum plus matching name table from one list: the macro removes the "update both places" bug.
@m colors($m)
$m(RED)
$m(GREEN)
$m(BLUE)
@tt
names:=["RED","GREEN","BLUE"]
items:=[]
for n names
items = push(items, "\"" + n + "\"")
emit("static const char *color_name[] = {" + join(items, ", ") + "};")
emit("enum Color { " + join(names, ", ") + ", COLOR_COUNT };")
f main()
for i := 0; i < COLOR_COUNT; i++
printf("%d = %s\n", i, color_name[i])
< 0
#include <stdio.h>
static const char *color_name[] = {"RED", "GREEN", "BLUE"};
enum Color {
RED,
GREEN,
BLUE,
COLOR_COUNT
};
int main(void) {
for (int i = 0; i < COLOR_COUNT; i++) {
printf("%d = %s\n", i, color_name[i]);
}
return 0;
}
Output
0 = RED
1 = GREEN
2 = BLUE
What it shows
@tt, enums