可变参数宏
声明语法
声明语法类似于可變參數函數:逗号后面三个句点"...",表示一个或多个参数。但常见编译器也允许传递0个参数。[2][3]宏扩展时使用特殊标识符__VA_ARGS__表示所传递的参数的替换。
没办法访问可变参数列表内的单个参数,也不能获知多少个参数被传递。[4]
实现支持
C/C++编译器支持:
- GNU Compiler Collection 3.0,[2]
- Clang ,[5]
- Visual Studio 2005,[3]
- C++Builder 2006,
- Oracle Solaris Studio (Sun Studio) Forte Developer 6 update 2 (C++ version 5.3).[6]
尾部逗号
对于可变参数为空情形,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__尾部逗号。
參見
参考文献
- Working draft changes for C99 preprocessor synchronization – http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1653.htm (页面存档备份,存于)
- . GNU Compiler Collection. [2017-04-01]. (原始内容存档于2020-07-04).
- . [2017-04-01]. (原始内容存档于2016-06-11).
- Laurent Deniau. . groups.google.com. 2006-01-16. Usenet: [email protected]. (原始内容存档于2012-11-07).
- 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%5B%5D
- 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.