__VA_ARGS__ does not expand correctly when no argument is given
It seems that there is a bug in expansion of __VA_ARGS__ for variable argument macros.
test1.c
#define debug(arg1, ... ) myfunc(arg1, __VA_ARGS__)
main() {
int i;
debug(i)
debug(i,i);
}
preprocessed output
-
bash-3.00$ cc -E testvar1.c
# 1 "testvar1.c"
# 3
main() {
int i;
"testvar1.c", line 7: warning: argument mismatch
myfunc ( i , )
^^^
myfunc ( i , i );
}
#ident "acomp: Sun C 5.8 Patch 121015-02 2006/03/29"
Notice the extra comma after the first argument in the first invocation.
Is this a bug or am I using it wrong?
[667 byte] By [
miteshriya] at [2007-11-26 10:23:58]

# 1
> Is this a bug or am I using it wrong?
Sorry, you are using it wrong. Or rather, defining it wrong. Preprocessor won't delete a comma in macro replacement list if a parameter appears to by an empty string. It just doesn't know that comma is smth special.
Correct macro definition would be
#define debug(...) myfunc(__VA_ARGS__)
# 3
Variable-argument macros are not officially part of C++. Sun C++ uses the C99 definition of variable-argument macros, which is likely to be adopted into the next C++ standard.
The C99 Standard says in the "Constraints" part of section 6.10.3, "there shall be more arguments in the invocation than there are parameters in the macro definition (excluding the ...)."
You can have a fixed argument in the macro definition
#define debug(arg1, ...) <something>
but you must have at least 2 arguments in each invocation.
if you want to be able to invoke the macro with one argument, the macro definition cannot have any fixed arguments.
The rule is different than for variable-argument functions. For variable-argument functions to work, the called function must have a first parameter of known type so that it can find the remainder of its arguments. There is no such problem for macros. Macro arguments do not have types, and the macro is completely expanded at compile time.
Message was edited by:
clamage45