C Snippets: X-Macros

c
code snippets
programming
A DRY, data driven technique using X macros in C.
Author

Christopher Andronikos

Published

July 15, 2020

Sometimes it is helpful to organise data in a form that can be drawn on in a flexible way so as to avoid unnecessary repetition.

#define TYPES(_) \
  _(double, x) \
  _(double, y) \
  _(double, z) \
  _(double, w)

The example above is an example of a table representing a 4 dimensional coordinate system. We can then make use of this table by writing another macro as follows:

#define AS_STRUCT(type, identifier) \
  type identifier;

This will expand within TYPES using the elements of each row as the arguments to the AS_STRUCT macro. Now we can declare a structure as follows:

typedef struct coord_4D {
 TYPES(AS_STRUCT)
} coord_4D;

We can also generate a function that will print out the elements of this structure as follows.

#define PRINT_ELEMENTS(type, identifier) \
  printf("type: %s, identifier: %s\n", #type, #identifier);

void print_elements(){
  printf("Elements of the structure coord_4D\n");
  TYPES(PRINT_ELEMENTS)
}

On another note, strings can be automatically concatenated allowing us to define PRINT_ELEMENTS as:

#define PRINT_ELEMENTS(type, identifier) \
  printf("type: " #type ", identifier: " #identifier "\n");

Citation

BibTeX citation:
@online{andronikos2020,
  author = {Andronikos, Christopher},
  title = {C {Snippets:} {X-Macros}},
  date = {2020-07-15},
  url = {https://candronikos.com/posts/2015-02-24-c-snippets-x-macros/},
  langid = {en}
}
For attribution, please cite this work as:
Andronikos, Christopher. 2020. “C Snippets: X-Macros.” July 15, 2020. https://candronikos.com/posts/2015-02-24-c-snippets-x-macros/.