X macros are an idiomatic usage of programming language macros for generating list-like structures of data or code. They are most useful when at least some of the lists cannot be composed by indexing, such as at compile time. They provide reliable maintenance of parallel lists whose corresponding items must be declared or executed in the same order.
Examples of such lists include initializing arrays, along with declaring enumeration constants and function prototypes, generating statement sequences and switch arms, etc.
Usage of X macros dates back to the 1960s. It remains useful in modern-day C and C++ programming languages, but remains relatively unknown.
An X macro application consists of two parts:
The list is defined by a macro or header file (named, <code>LIST</code>) which generates no code by itself, but merely consists of a sequence of invocations of a macro (classically named "<code>X</code>") with the elements' data. Each expansion of <code>LIST</code> is preceded by a definition of <code>X</code> with the syntax for a list element. The invocation of <code>LIST</code> expands <code>X</code> for each element 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.
Then we expand this list to generate the variable declarations:
In a similar way, we can generate a function that prints the variables and their values:
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:
This example aims to improve the readability of the X macro usage by:
As above, execute this list to generate the variable declarations:
or declare an enumeration:
In a similar way, we can generate a function that prints the variables and their names: