Easy C preprocessor patterns

This is a guide for someone who is using C day to day, to use preprocessor more efficiently. Or to look more like a mad man and get murdered by the next person who will have to inherit the code.

Fascination

I do not quite understand what I find exactly so mysterious about C preprocessor. It is indeed like small puzzles, small Legos scattered around, that you can connect together and maybe built some oddly looking monster no one will want to look at. The Legos are really specific, from a really cheap off-brand, not all match together. You have to be either really clever or use a big hammer, or both, to finally piece two Legos together.

I spent a lot of time researching C preprocessor and answering sane C preprocessor related questions on Stack Overflow. I do not think when I write yet another macro, overloaded on number of arguments. Furthermore, I’ve written code generating C preprocessor code in PHP, Jinja2, m4, and also in C itself.

C preprocessor is limited. You should not use it. You should use Rust macros or C++ templates. I believe the combination of that “forbidden knowledge” smell and the really oddly shaped puzzles create this specific environment where what you do is fun, fulfilling and exciting.

Overload on number of arguments.

Overloading a macro on number of arguments has been my base for any transformations. I say it is really important and this is the most useful transformation I use. I throw it basically anytime I have to do something, as more often than not, I want to handle many arguments or default arguments in macros.

Preprocessor does not have loops. You almost have to write out every single case. You can use recursive expansion, but I found that no one ever writes code that uses it, only C preprocessor maniacs. While it is great, and such people understand it, I do not see such code written on stack overflow to solve real life problems. I understand recursive expansion is used to solve interesting problems and write libraries by people well versed in C preprocessor.

I want my code to be simple, readable, easy to follow. The EVAL(EVAL(EVAL( results in unmaintainable code and unreadable error messages. I do not want that. At least I try to. I do not see real-life good examples of using recursive expansion. Additionally, there is one big problem with recursion in macro – you are not able to pass state. You can expand, up down, but you can’t pass state to the side, which is very, very limiting in many cases.

Macro concatenation to get another macro.

For the purpose of this article, let’s write a FOREACH macro that will handle up to 4 arguments. That number of arguments is enough to see the pattern to how to generate such code with a template language.

The FOREACH macro will apply a macro f taken by argument on each of the arguments. The hearth of a macro overload on arguments is what I call an “arguments shifting macro”. And I do apologize in advance for my names.

#define FOREACH_N(_4,_3,_2,_1,N,...)  FOREACH##N
#define FOREACH(f, ...)               FOREACH_N(__VA_ARGS__,_4,_3,_2,_1)(f, __VA_ARGS__)

Firstly, we can see that the pattern _4,_3,_2,_1 is repeated twice. This is a hint if you want to generate the code with a template language. The arguments f before ... jumps to the end on (f, __VA_ARGS__) repeating all the arguments the macro received.

The FOREACH_N exists to pick a suffix of the next macro that will be called depending on the number of arguments. With one argument, N will be _1, in which case FOREAHC##N will become FOREACH_1. With two arguments, N will be _2, and so on.

The number of arguments “shifts” the chain to the right, causing N to land on a number more to the left.

                             FOREACH_N(_4, _3, _2, _1,  N, ...)
FOREACH(f, a)             -> FOREACH_N( a, _4, _3, _2, _1)
FOREACH(f, a, b)          -> FOREACH_N( a,  b, _4, _3, _2, _1)
FOREACH(f, a, b, c)       -> FOREACH_N( a,  b,  c, _4, _3, _2, _1)
FOREACH(f, a, b, c, d)    -> FOREACH_N( a,  b,  c,  d, _4, _3, _2, _1)
FOREACH(f, a, b, c, d, e) -> FOREACH_N( a,  b,  c,  d,  e, _4, _3, _2, _1)

If we pass more arguments than cases, then oops – N becomes the 5th argument. Usually this is not handled, and user is greeted with some error message.

Cases

Then we have to write each individual cases. There are two styles that I use. The “plain” style is just where you list all the cases one by one:

#define FOREACH_1(f, a)           f(a)
#define FOREACH_2(f, a, b)        f(a) f(b)
#define FOREACH_3(f, a, b, c)     f(a) f(b) f(c)
#define FOREACH_4(f, a, b, c, d)  f(a) f(b) f(c) f(d)

Another one is the “call previous” style, where every expansion on level N calls the expansion from N-1.

#define FOREACH_1(f, a)       f(a)
#define FOREACH_2(f, a, ...)  f(a) FOREACH_1(f, __VA_ARGS__)
#define FOREACH_3(f, a, ...)  f(a) FOREACH_2(f, __VA_ARGS__)
#define FOREACH_4(f, a, ...)  f(a) FOREACH_3(f, __VA_ARGS__)

In the end of the day, the plain style should be preferred. But I hear – the “call previous” is easier to write, less to type, easier to generate. Yes. And I still use it, when I am lazy. But the problem is in error messages.

Every time you descend in another expansion, GCC will generate yet another one of “note: in expansion of” message in case of error. With the call previous style, if the error happens to be in the last case in 4 cases, you will get a wall of 4 “note: in expansion of” messages. With many more cases and nested macros usages, shovels just break when trying to dig through the depths of walls of texts from the compiler. The plain style results in few expansions, saving memory of the compiler and saving you the time to read the error messages. Prefer it whenever possible.

Altogether, the macro looks like the following, with a small usage example of a program existing with 10:

#define FOREACH_1(f, a)           f(a)
#define FOREACH_2(f, a, b)        f(a) f(b)
#define FOREACH_3(f, a, b, c)     f(a) f(b) f(c)
#define FOREACH_4(f, a, b, c, d)  f(a) f(b) f(c) f(d)
#define FOREACH_N(_4,_3,_2,_1,N,...)  FOREACH##N
#define FOREACH(f, ...) FOREACH_N(__VA_ARGS__,_4,_3,_2,_1)(f, __VA_ARGS__)

#define PLUS(x)  + x
int main() {
    return 0 FOREACH(PLUS, 1, 2, 3, 4);  // return 0 + 1 + 2 + 3 + 4;
}

Style

And let’s talk a little bit about the style. Firstly, indentation. The rule is that there have to be at least two spaces separating macro right parenthesis ) from the replacement. This is to visually distinguish the replacement from the macro definition.

#define FOREACH_4(f, a, b, c, d)  f(a) f(b) f(c) f(d)
//                  ^  ^  ^  ^        ^    ^    ^      - one space
//                              ^^                     - two spaces

While I usually write _4,_3,_2,_1, as one block without spaces, I wouldn’t mind the spaces if they were added by a tool, or by other programmers. That’s fine. That is usually anyway just a long list of _63, _62, _61, ....... numbers.

Secondly, I usually align all FOREACH on one column to visually see all the names:

#define FOREACH_N(_4,_3,_2,_1,N,...)  \
        FOREACH##N
#define FOREACH(f, ...)  \
        FOREACH_N(__VA_ARGS__,_4,_3,_2,_1)(f, __VA_ARGS__)

This is really helpful in case of renames. You see all the FOREACH aligned together, and it is quite clear what should be renamed in case you want to change the macro name.

If the list of numbers is long, not many people know that you can break a macro definition mid-parameter list.

#define FOREACH_N(_4, _3, _2, _1, \
        N, ...)  \ FOREACH##N
#define FOREACH(f, ...)  \
        FOREACH_N(__VA_ARGS__, _4, _3, _2, _1) \ (f, __VA_ARGS__)

That way, even if the list _4,_3,_2,_1 is very long, you still visually see to the left what is going on. The N is left aligned, the (f,
__VA_ARGS__)
is immediately visible.

Finally, you see people writing the following code, saving the _ in the “arguments shifting macro” call:

#define FOREACH_N(_4,_3,_2,_1,N,...)  FOREACH_##N
#define FOREACH(f, ...)               FOREACH_N(__VA_ARGS__,4,3,2,1)(f, __VA_ARGS__)

This is great and acceptable, it just has one drawback. When using code generation, you have to write two functions – one to generate _4,_3,_2,_1 and then to generate 4,3,2,1. It is not much, but it is much simpler to just generate one sequence and reuse it in two places. Or in other words, when writing by hand, I can just select _4,_3,_2,_1 and copy it to the call, instead of retyping it.

Default arguments

Knowing the basics, it is trivial to implement some use cases. The following implements a function call with default arguments:

#include <stdio.h>

enum {
   LOG_LVL_DEFAULT = 0, lOG_ERROR = 1,
};

void log(FILE *, int lvl, const char *msg) {}

#define LOG_1(msg)             log(stderr, LOG_LVL_DEFAULT, msg)
#define LOG_2(file, msg)       log(  file, LOG_LVL_DEFAULT, msg)
#define LOG_3(file, lvl, msg)  log(  file,             lvl, msg)
#define LOG_N(_3,_2,_1,N,...)  LOG##N
#define LOG(...)               LOG_N(__VA_ARGS__,_3,_2,_1)(__VA_ARGS__)

int main() {
    LOG("hello world");                      // log(stderr, LOG_LVL_DEFAULT, "hello world");
    LOG(stdout, "hello world");              // log(stdout, LOG_LVL_DEFAULT, "hello world");
    LOG(stdout, LOG_ERROR, "hello world");   // log(stdout, LOG_ERROR, "hello world");
}

While this example is not particularly useful, it shows how incredibly easy it is to build a function call with default arguments, also in any other.

Leave a Comment

Scroll to Top