可变参数宏

可变参数宏C语言C++语言函数宏的参数个数可以是0个或多个。这一语言特性由C99引入。C++11也开始支持。[1]

声明语法

声明语法类似于可變參數函數:逗号后面三个句点"...",表示一个或多个参数。但常见编译器也允许传递0个参数。[2][3]宏扩展时使用特殊标识符__VA_ARGS__表示所传递的参数的替换。

没办法访问可变参数列表内的单个参数,也不能获知多少个参数被传递。[4]

实现支持

C/C++编译器支持:

尾部逗号

对于可变参数为空情形,Visual Studio[3]直接去掉可变参数前面的逗号;GCC[2]需要在__VA_ARGS__前面放上##以去除逗号。

# define MYLOG(FormatLiteral, ...)  fprintf (stderr, "%s(%d): " FormatLiteral "\n", __FILE__, __LINE__, __VA_ARGS__)

对于

MYLOG("Too many balloons %u", 42);

扩展为:

fprintf (stderr, "%s(%u): " "Too many balloons %u" "\n", __FILE__, __LINE__, 42);

它等价于:

fprintf (stderr, "%s(%u): Too many balloons %u\n", __FILE__, __LINE__, 42);

但对于例子:

MYLOG("Attention!");

扩展为

fprintf (stderr, "%s(%u): " "Attention!" "\n", __FILE__, __LINE__, );

GCC将会编译报错.

GCC支持下述不可移植的扩展:

# define MYLOG(FormatLiteral, ...)  fprintf (stderr, "%s(%u): " FormatLiteral "\n", __FILE__, __LINE__, ##__VA_ARGS__)

这将删除空的__VA_ARGS__尾部逗号。

參見

参考文献

  1. Working draft changes for C99 preprocessor synchronization – http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1653.htm
  2. Variadic Macros – Using the GNU Compiler Collection (GCC)
  3. Variadic Macros (C++)
  4. Laurent Deniau. . Newsgroup: comp.std.c 请检查|url=值 (帮助). 2006-01-16. Usenet: dqgm2f$ije$1@sunnews.cern.ch.
  5. Clang source code change that mentions __VA_ARGS__ support (2006-07-29), note that Clang was open-sourced in 2007. http://llvm.org/viewvc/llvm-project?view=revision&revision=38770
  6. Sun Studio feature comparison – http://developers.sun.com/sunstudio/support/CCcompare.html
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.