lxvs
lxvs

Reputation: 1030

Variadic macros in C

In GNU documentation on variadic macros, an example is

#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)

...

In standard C, you are not allowed to leave the variable argument out entirely; but you are allowed to pass an empty argument. For example, this invocation is invalid in ISO C, because there is no comma after the string:

debug ("A message")

Also GNU gave a solution:

#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)

I wonder why not use the below definition

#define debug(...) fprintf (stderr, __VA_ARGS__)

so that it can be compliant with Standard C, as well as more concise and intuitive?

Upvotes: 0

Views: 328

Answers (1)

Shawn
Shawn

Reputation: 52336

#define debug(...) fprintf (stderr, __VA_ARGS__)

This allows for debug(), which expands to fprintf (stderr, ), which is of course invalid syntax.

And with

#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)

using debug("A message") similarly becomes fprintf (stderr, "A message", ), which as the documentation alludes to, is also an error (and apparently invalid in standard C, which would need debug("A message", ) which leads to the same flawed expansion). You should just use debug("%s", "A message") instead, which works with either definition without relying on compiler specific extensions (and addresses the issue of what happens when the string to print has a % in it).


You're looking at documentation for an ancient gcc release; newer ones have rewritten that section to be clearer (and have another option besides ## to address the issue, taken from C++20).

Upvotes: 1

Related Questions