C中具有2个以上参数的大小写可变参数宏

此问题中接受的答案回答了如何创建一个宏,该宏将从2个可用的其他宏中进行选择(一个采用1个参数,另一个采用2个参数)。

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

如果有问题的2个宏具有4和5个参数,而不是1和2,那么如何编写代码?

jerrytoto 回答:C中具有2个以上参数的大小写可变参数宏

对1到5个变量采用相同的方法。它也可以扩展到更多。

#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,x3,x4)   printf("%d\n",x1 + x2 + x3 + x4);
#define VAR_5(x1,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,2,3);
    VAR(0,3,4);
    return 0;
}

本文链接:https://www.f2er.com/2947625.html

大家都在问