【问题标题】:What does __VA_ARGS__ in a macro mean?宏中的 __VA_ARGS__ 是什么意思?
【发布时间】:2014-11-21 03:13:19
【问题描述】:
/* Debugging */
#ifdef DEBUG_THRU_UART0
# define DEBUG(...) printString (__VA_ARGS__)
#else
void dummyFunc(void);
# define DEBUG(...) dummyFunc()
#endif
我在C编程的不同头文件中看到过这种表示法,我基本理解它是传递参数,但我不明白这个“三点表示法”叫什么?
有人可以用例子解释它或提供关于 VA Args 的链接吗?
【问题讨论】:
标签:
c
gcc
variadic-macros
variadic-functions
【解决方案1】:
点与__VA_ARGS__ 一起被调用,可变参数宏
调用宏时,其参数列表中的所有标记 [...],包括任何逗号,
成为可变参数。这个令牌序列取代了
标识符 VA_ARGS 出现在宏正文中。
source,我的大胆强调。
使用示例:
#ifdef DEBUG_THRU_UART0
# define DEBUG(...) printString (__VA_ARGS__)
#else
void dummyFunc(void);
# define DEBUG(...) dummyFunc()
#endif
DEBUG(1,2,3); //calls printString(1,2,3) or dummyFunc() depending on
//-DDEBUG_THRU_UART0 compiler define was given or not, when compiling.
【解决方案2】:
这是一个variadic 宏。这意味着您可以使用任意数量的参数调用它。三个... 类似于C 中variadic function 中使用的相同构造
这意味着你可以像这样使用宏
DEBUG("foo", "bar", "baz");
或者带有任意数量的参数。
__VA_ARGS__ 再次引用宏本身中的变量参数。
#define DEBUG(...) printString (__VA_ARGS__)
^ ^
+-----<-refers to ----+
所以DEBUG("foo", "bar", "baz"); 将被替换为printString ("foo", "bar", "baz")