Reputation: 333
I would like to know what ##
does in this macro definition:
#define debug(M, ...) fprintf(stderr,M "\n",##__VA_ARGS__)
I googled for an answer and I came up with the following.
The ##
will remove the comma if no variable arguments are given to the macro. So, if the macro is invoked like this
debug("message");
with no quotes, it is expanded to
fprintf(stderr,"message");
not
fprintf(stderr,"message",);
Why is the comma removed?
Upvotes: 23
Views: 57436
Reputation: 651
from https://en.cppreference.com/w/cpp/preprocessor/replace
Note: some compilers offer an extension that allows ## to appear after a
comma and before __VA_ARGS__, in which case the ## does nothing when the
variable arguments are present, but removes the comma when the variable
arguments are not present: this makes it possible to define macros such as
fprintf (stderr, format, ##__VA_ARGS__)
Upvotes: 2
Reputation: 6287
It's a non-portable syntax introduced by gcc to specifically deal with this corner case of passing no arguments at all. Without the ## it would complain about the trailing comma being a syntax error.
https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
C++20 introduced __VA_OPT__
for this purpose:
https://en.cppreference.com/w/cpp/preprocessor/replace
Upvotes: 25