c中的变异宏

发布于 2025-01-29 05:21:40 字数 820 浏览 3 评论 0 原文

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你与清晨阳光 2025-02-05 05:21:40
#define debug(...) fprintf (stderr, __VA_ARGS__)

这允许 debug(),它将扩展到 fprintf(stderr,),这当然是无效的语法。

并且

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

使用调试(“ a takes”)同样变成 fprintf(stderr,“ a temess”,),(如文档所暗示)也是错误(并且显然在标准C中无效,它需要 debug(“消息”,),导致相同的有缺陷的扩展)。您应该只使用 debug(“%s”,“一个消息”),它可以与任何一个定义一起使用,而无需依赖编译器特定的扩展(并解决当要打印的字符串打印具有的问题的问题其中一个%)。


您正在查看古代海湾合作委员会发行的文档; ## 以外,还有另一个选项,以解决该问题,从C ++ 20中获取)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文