Variadic Macros is function-like macros that contain a variable number of arguments.Remarks
To use Variadic macros, the ellipsis is specified as the final formal argument in a macro definition, and the Replacem ENT identifier __va_args__ May is used in the definition to insert the extra arguments. __va_args__ is replaced by all of the arguments that match the ellipsis, including commas between them.
The C standard specifies in least one argument must be passed to the ellipsis, to ensure that the macro does not Reso Lve to an expression with a trailing comma. The Visual C + + implementation would suppress a trailing comma if no arguments is passed to the ellipsis.
ExampleC++
Variadic_macros.cpp#include <stdio.h> #define Empty#define CHECK1 (x, ...) if (! ( x) {printf (__va_args__);} #define CHECK2 (x, ...) if ((x)) {printf (__va_args__);} #define CHECK3 (...) {printf (__va_args__);} #define MACRO (S, ...) printf (s, __va_args__) int main () { CHECK1 (0, "Here%s%s", "is", "some", "varargs1 (1) \ n");
check1 (1, "Here%s%s", "is", "some", "varargs1 (2) \ n"); Won ' t print CHECK2 (0, "Here%s%s", "is", "some", "VARARGS2 (3) \ n"); Won ' t print CHECK2 (1, "Here%s%s", "is", "some", "VARARGS2 (4) \ n"); Always invokes printf in the macro CHECK3 ("Here%s%s", "is", "some", "VARARGS3 (5) \ n"); MACRO ("Hello, world\n"); MACRO ("error\n", EMPTY); Would cause error C2059, except VC + +/ suppresses the trailing comma}
Output
Here is some varargs1 (1) Here is some varargs2 (4) Here is some varargs3 (5) Hello, worlderror
C++11:variadic Macros (variable length parameter macro)