Next:Escaped Newlines, Previous:Variable Length, Up:C Extensions [Contents][Index]
In the ISO C standard of 1999, a macro can be declared to accept avariable number of arguments much as a function can. The syntax fordefining the macro is similar to that of a function. Here is anexample:
#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
Here ‘…’ is avariable argument. In the invocation ofsuch a macro, it represents the zero or more tokens until the closingparenthesis that ends the invocation, including any commas. This set oftokens replaces the identifier__VA_ARGS__ in the macro bodywherever it appears. See the CPP manual for more information.
GCC has long supported variadic macros, and used a different syntax thatallowed you to give a name to the variable arguments just like any otherargument. Here is an example:
#define debug(format, args...) fprintf (stderr, format, args)
This is in all ways equivalent to the ISO C example above, but arguablymore readable and descriptive.
GNU CPP has two further variadic macro extensions, and permits them tobe used with either of the above forms of macro definition.
In standard C, you are not allowed to leave the variable argument outentirely; but you are allowed to pass an empty argument. For example,this invocation is invalid in ISO C, because there is no comma afterthe string:
debug ("A message")GNU CPP permits you to completely omit the variable arguments in thisway. In the above examples, the compiler would complain, though sincethe expansion of the macro still has the extra comma after the formatstring.
To help solve this problem, CPP behaves specially for variable argumentsused with the token paste operator, ‘##’. If instead you write
#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
and if the variable arguments are omitted or empty, the ‘##’operator causes the preprocessor to remove the comma before it. If youdo provide some variable arguments in your macro invocation, GNU CPPdoes not complain about the paste operation and instead places thevariable arguments after the comma. Just like any other pasted macroargument, these arguments are not macro expanded.
Next:Escaped Newlines, Previous:Variable Length, Up:C Extensions [Contents][Index]