Tutorial by Examples

/* define a list of preprocessor tokens on which to call X */ #define X_123 X(1) X(2) X(3) /* define X to use */ #define X(val) printf("X(%d) made this print\n", val); X_123 #undef X /* good practice to undef X to facilitate reuse later on */ This example will result in the prep...
/* declare items of the enum */ #define FOREACH \ X(item1) \ X(item2) \ X(item3) \ /* end of list */ /* define the enum values */ #define X(id) MyEnum_ ## id, enum MyEnum { FOREACH }; #undef X /* convert an enum value to its identifier */ const char * enum2string(int...
The X-macro approach can be generalized a bit by making the name of the "X" macro an argument of the master macro. This has the advantages of helping to avoid macro name collisions and of allowing use of a general-purpose macro as the "X" macro. As always with X macros, the mas...
X-Macros can be used for code generation, by writing repetitive code: iterate over a list to do some tasks, or to declare a set of constants, objects or functions. Here we use X-macros to declare an enum containing 4 commands and a map of their names as strings Then we can print the string values ...

Page 1 of 1