Created
August 22, 2025 18:34
-
-
Save wpcarro/622f368026ef28a41e090c9f1b35ec5d to your computer and use it in GitHub Desktop.
X-macros for enums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| // Fully connected graph of transformations: | |
| // Message (enum) | |
| // MessageIndex (enum) | |
| // | |
| // Index -> Key | |
| // Index -> Value | |
| // Value -> Index (reverse lookup) | |
| #define MESSAGES(X) \ | |
| X(FOO, 0) \ | |
| X(BAR, 1) \ | |
| X(BAZ, 2) \ | |
| X(BOK, 7) | |
| #define ENUM_KV(key, val) key = val, | |
| #define ENUM_IDX(key, val) IDX_##key, | |
| #define ENUM_KEYS(key, val) #key, | |
| #define ENUM_VALS(key, val) val, | |
| #define ENUM_CASES(key, val) case(key): { return IDX_##key; } | |
| #define GEN_ENUM(name, max, xs) \ | |
| typedef enum { xs(ENUM_KV) } name; \ | |
| enum { xs(ENUM_IDX) max }; \ | |
| static const char *keys[max] = { xs(ENUM_KEYS) }; \ | |
| static const int vals[max] = { xs(ENUM_VALS) }; \ | |
| int index_of(name x) { \ | |
| switch(x) { \ | |
| xs(ENUM_CASES) \ | |
| default: { return -1; } \ | |
| } \ | |
| } | |
| GEN_ENUM(Message, NUM_MESSAGES, MESSAGES) | |
| int main(void) { | |
| for (size_t i = 0; i < NUM_MESSAGES; i += 1) { | |
| Message msg = vals[i]; | |
| printf("[%zu] \"%s\": %d\n", i, keys[i], vals[i]); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment