c / expert
Snippet
X-Macros for Data Synchronization
X-Macros are a preprocessor technique for generating repetitive code from a single master list. This ensures that enums, string arrays, and other related structures remain synchronized, reducing maintenance errors and improving code consistency.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define STATUS_LIST \X(IDLE, "System is waiting") \X(BUSY, "Processing task") \X(ERROR, "Fatal failure")typedef enum {#define X(name, desc) STATUS_##name,STATUS_LIST#undef X} Status;const char* status_strings[] = {#define X(name, desc) desc,STATUS_LIST#undef X};// Usage: status_strings[STATUS_BUSY] returns "Processing task"
Breakdown
1
#define STATUS_LIST X(IDLE, ...) ...
Defines a master list where each entry is wrapped in a placeholder macro 'X'.
2
#define X(name, desc) STATUS_##name,
Redefines 'X' to generate enum members, then expands the master list.
3
#undef X
Undefines 'X' so it can be redefined later for a different purpose (like generating strings).