在 variadic macros上的gnu文档示例是
#define debug(format,...)fprintf(stderr,格式,__va_args__)
...
在标准C中,不允许您完全排除变量参数;但是您可以通过一个空的论点。例如,此调用在ISO C中无效,因为字符串之后没有逗号:
debug(“ a messages”)
GNU给出了一个解决方案:
#define debug(格式,...)
我想知道为什么不使用以下定义
#define debug(...) fprintf (stderr, __VA_ARGS__)
,以便它可以符合标准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?
发布评论
评论(1)
这允许
debug()
,它将扩展到fprintf(stderr,)
,这当然是无效的语法。并且
使用
调试(“ a takes”)
同样变成fprintf(stderr,“ a temess”,),
(如文档所暗示)也是错误(并且显然在标准C中无效,它需要debug(“消息”,)
,导致相同的有缺陷的扩展)。您应该只使用debug(“%s”,“一个消息”)
,它可以与任何一个定义一起使用,而无需依赖编译器特定的扩展(并解决当要打印的字符串打印具有的问题的问题其中一个%)。您正在查看古代海湾合作委员会发行的文档; ## 以外,还有另一个选项,以解决该问题,从C ++ 20中获取)。
This allows for
debug()
, which expands tofprintf (stderr, )
, which is of course invalid syntax.And with
using
debug("A message")
similarly becomesfprintf (stderr, "A message", )
, which as the documentation alludes to, is also an error (and apparently invalid in standard C, which would needdebug("A message", )
which leads to the same flawed expansion). You should just usedebug("%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).