免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 817 | 回复: 0
打印 上一主题 下一主题

Macros with a Variable Number of Arguments [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-15 13:27 |只看该作者 |倒序浏览
5.14 Macros with a Variable Number of Arguments.
In the ISO C standard of 1999, a macro can be declared to accept a variable number of
arguments much as a function can. The syntax for defining the macro is similar to that of
a function. Here is an example:
#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
Here ‘...’ is a variable argument. In the invocation of such a macro, it represents the
zero or more tokens until the closing parenthesis that ends the invocation, including any
commas. This set of tokens replaces the identifier __VA_ARGS__ in the macro body wherever
it appears. See the CPP manual for more information.
GCC has long supported variadic macros, and used a different syntax that allowed you
to give a name to the variable arguments just like any other argument. Here is an example:
#define debug(format, args...) fprintf (stderr, format, args)
This is in all ways equivalent to the ISO C example above, but arguably more readable
and descriptive.
GNU CPP has two further variadic macro extensions, and permits them to be used with
either of the above forms of macro definition.
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")
GNU CPP permits you to completely omit the variable arguments in this way. In the
above examples, the compiler would complain, though since the expansion of the macro still
has the extra comma after the format string.
To help solve this problem, CPP behaves specially for variable arguments used with the
token paste operator, ‘##’. If instead you write
#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
and if the variable arguments are omitted or empty, the ‘##’ operator causes the preprocessor
to remove the comma before it. If you do provide some variable arguments in
your macro invocation, GNU CPP does not complain about the paste operation and instead
places the variable arguments after the comma. Just like any other pasted macro argument,
these arguments are not macro expanded.
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/59445/showart_1863808.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP