Search code examples
cmacrosc-preprocessor

How to have a macro expand into the arg name of another macro


for example:

#define Y (b * 2)
#define X(b) Y

int main()
{
    printf("%d", X(4)); // Want it to print 8, but doesn't work
}

Is something like this possible with C macros?


Solution

  • As mentioned in comments, the macro parameter name has local scope to the specific function-like macro, so you can't access it from outside the macro.

    Something similar is possible with the design pattern known as "X macros" though. It is based on providing a list (or a single item) of data in a macro, than have that list macro take a different macro as parameter, in order to apply something to the list of data.

    Example:

    #include <stdio.h>
    
    // here X will be an external function-like macro with 1 parameter:
    #define LIST(X) \
      X(4)          \
      X(8)
    
    // some macros with 1 parameter that should print and possibly also multiplicate
    #define PRINTx1(a) printf("%d ", (a));  // note the semicolon here
    #define PRINTx2(a) printf("%d ", (a)*2);
    
    int main (void)
    {
      LIST(PRINTx1)  // note the lack of semicolon here
      puts("");
      LIST(PRINTx2)
    }
    

    Output:

    4 8 
    8 16 
    

    All of the above will expand like this:

    PRINTx1(4) PRINTx1(8)
    puts("");
    PRINTx2(4) PRINTx2(8)
    

    ->

    printf("%d ", (4)); printf("%d ", (8));
    puts("");
    printf("%d ", (4)*2); printf("%d ", (8)*2);