X Macro

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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]


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.


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.

    X(value1) \
    X(value2) \

Then we execute this list to generate the variable declarations:

#define X(name) int name;
#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);
#undef X

When run through the C preprocessor, the following code is generated. Line breaks and indentation 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[edit]


  1. ^ Meyers, Randy. The New C: X Macros. Dr.Dobb's 2001.
  2. ^ Bright, Walter. The X Macro. Dr.Dobb's 2010
  3. ^ Lucas, Andrew. Reduce C-language coding errors with X macros. Embedded.com 2013.