X Macro
X Macro is a technique in the C programming language 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, but is nevertheless relatively unknown.[2]
Contents |
Implementation [edit]
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 [edit]
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:
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 [edit]
References [edit]
- ^ Meyers, Randy. The New C: X Macros. Dr.Dobb's 2001.
- ^ Bright, Walter. The X Macro. Dr.Dobb's 2010