Sun Studio 12: C User's Guide

D.1.16 Macros With a Variable Number of Arguments

6.10.3 Macro replacement

The C compiler accepts #define preprocessor directives of the following form:


#define identifier (...) replacement_list
#define identifier (identifier_list, ...) replacement_list

If the identifier_list in the macro definition ends with an ellipses, it means that there will be more arguments in the invocation than there are parameters in the macro definition, excluding the ellipsis. Otherwise, the number of parameters in the macro definition, including those arguments which consist of no preprocessing tokens, matches the number of arguments. Use the identifier __VA_ARGS__ in the replacement list of a #define preprocessing directive which uses the ellipsis notation in its arguments. The following example demonstrates the variable argument list macro facilities.


#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);

which results in the following:


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));