21

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mohammed Micro
  • 313
  • 1
  • 2
  • 5

2 Answers2

22

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

Trass3r
  • 5,858
  • 2
  • 30
  • 45
2

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__)
waterd
  • 603
  • 1
  • 7
  • 23