0

The accepted answer in this question answers how to create a macro that would choose from 2 available other macros (one taking 1 parameter and the other taking 2).

https://stackoverflow.com/a/55075214/1036082

How to write the code in case the 2 macros in question had 4 and 5 parameters, not 1 and 2?

Łukasz Przeniosło
  • 2,725
  • 5
  • 38
  • 74

1 Answers1

2

This is taking the same approach for 1 to 5 variables. It can also be expanded to more.

#define VAR_1(x1)   printf("%d\n", x1);
#define VAR_2(x1, x2)   printf("%d\n", x1 + x2);
#define VAR_3(x1, x2, x3)   printf("%d\n", x1 + x2 + x3);
#define VAR_4(x1, x2, x3, x4)   printf("%d\n", x1 + x2 + x3 + x4);
#define VAR_5(x1, x2, x3, x4, x5)   printf("%d\n", x1 + x2 + x3 + x4 + x5);

#define GET_MACRO(_1, _2, _3, _4, _5, NAME, ...) NAME
#define VAR(...) GET_MACRO(__VA_ARGS__, VAR_5, VAR_4, VAR_3, VAR_2, VAR_1, DUMMY)(__VA_ARGS__)
/* The DUMMY element is required to avoid the warning: "ISO C99
   requires rest arguments to be used" when compiled with -pedantic" */

int main(void)
{
    VAR(0);
    VAR(0, 1);
    VAR(0, 1, 2);
    VAR(0, 1, 2, 3);
    VAR(0, 1, 2, 3, 4);
    return 0;
}

hko
  • 548
  • 2
  • 19