Search code examples
cmacros

Recursive C Macros


Question

Suppose I want to define a certain number of unique variables like so:

int toto0 = 0;
int toto1 = 0;
int toto2 = 0;

How can this be achieved with a single macro to which you pass a number, say like:

#define TOTO(n) // Magic

Investigations

I have looked into several SO answers, and one seemed particularly interesting for the topic: here

It basically describes an implementation of a mapping macro, and for my application I can achieve the desired result like so:

#define VAR(x) uint32_t toto##x = 0;
// Call to MAP
MAP(VAR,0,1,2)
// or using __COUNTER__
MAP(VAR,__COUNTER__,__COUNTER__,__COUNTER__)

However, it is not exactly the TOTO(n) concise macro, and would require me writing out all the parameters! Maybe again using a similar technique to the linked SO answer there is a way to expand __COUNTER__ n times and plug it into the function?


Solution

  • How can this be achieved with a single macro to which you pass a number, say like:

    #define TOTO(n) // Magic
    

    It cannot be achieved by and with a single macro.

    Macro expansion is explicitly non-recursive (C23 6.10.5.5/2). You can produce limited-depth recursion-like effects via a suitable stack of multiple macros, but that gets ugly and hard to maintain very quickly. For even moderately complex code generation you would probably be best off writing a separate code generator.