X Macro
X Macro is a technique in the C and C++ programming languages for generating repeating code structures at compile time. It is used when the same operation has to be executed for a list of items, but regular for loops cannot be used.
Usage of X Macros dates back to 1960's.[1] It remains useful also in modern-day C and C++, but is nevertheless relatively unknown.[2] [3]
Implementation
An X-macro consists of two parts: the list, and the execution of the list. The list is just a #define construct which generates no code by itself. The execution of the list provides another #define macro, which is expanded for each entry in the list.
Example
This example defines a list of variables, and automatically generates their declarations and a function to print them out.
First the list definition. The list entries could contain multiple arguments, but here only the name of the variable is used.
#define LIST_OF_VARIABLES \
X(value1) \
X(value2) \
X(value3)
Then we execute this list to generate the variable declarations:
#define X(name) int name; LIST_OF_VARIABLES #undef X
In a similar way, we can generate a function that prints the variables and their names:
void print_variables() { #define X(name) printf(#name " = %d\n", name); LIST_OF_VARIABLES #undef X }
When run through the C preprocessor, the following code is generated. Line breaks have been added for ease of reading, even though they are not actually generated by the preprocessor:
int value1; int value2; int value3; void print_variables() { printf("value1" " = %d\n", value1); printf("value2" " = %d\n", value2); printf("value3" " = %d\n", value3); }
Further reading
References
- ↑ Meyers, Randy. The New C: X Macros. Dr.Dobb's 2001.
- ↑ Bright, Walter. The X Macro. Dr.Dobb's 2010
- ↑ Lucas, Andrew. Reduce C-language coding errors with X macros. Embedded.com 2013.