C++ 编译器接受以下形式的 #define 预处理程序指令。
#define identifier (...) replacement-list #define identifier (identifier-list, ...) replacement-list
如果列出的宏参数以省略号结尾,那么该宏的调用允许使用除了宏参数以外的其他更多参数。其他参数(包括逗号)收集到一个字符串中,宏替换列表中的名称 __VA_ARGS__ 可以引用该字符串。
以下示例说明了如何使用可变参数列表的宏。
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define showlist(...) puts(#__VA_ARGS__)
#define report(test, ...) ((test)?puts(#test):\
printf(__VA_ARGS__))
debug(“Flag”);
debug(“X = %d\n”,x);
showlist(The first, second, and third items.);
report(x>y, “x is %d but y is %d”, x, y);其结果如下:
fprintf(stderr, “Flag”); fprintf(stderr, “X = %d\n”, x); puts(“The first, second, and third items.”); ((x>y)?puts(“x>y”):printf(“x is %d but y is %d”, x, y));