0

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?

2
  • 2
    The example in the documentation is just an example. Not every macro can be written with a single ... argument. Commented May 15, 2022 at 14:05
  • One reason is that it makes it unclear what you should pass to debug. With the explicit format, you know what's expected. Commented May 15, 2022 at 14:10

1 Answer 1

1
#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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.