##__VA_ARGS__ 是什么意思?
What does ##__VA_ARGS__ mean?
我想知道##
在这个宏定义中做了什么:
#define debug(M, ...) fprintf(stderr,M "\n",##__VA_ARGS __)
我用谷歌搜索了一个答案,然后得出了以下结果。
如果没有为宏提供可变参数,##
将删除逗号。所以,如果像这样调用宏
debug("message");
没有引号,扩展为
fprintf(stderr,"message");
没有
fprintf(stderr,"message",);
为什么去掉了逗号?
这是 gcc 引入的一种不可移植的语法,专门处理这种根本不传递任何参数的极端情况。
如果没有 ##,它会抱怨尾随逗号是语法错误。
https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
C++20 为此引入了 __VA_OPT__
:
https://en.cppreference.com/w/cpp/preprocessor/replace
来自 https://en.cppreference.com/w/cpp/preprocessor/replace
Note: some compilers offer an extension that allows ## to appear after a
comma and before __VA_ARGS__, in which case the ## does nothing when the
variable arguments are present, but removes the comma when the variable
arguments are not present: this makes it possible to define macros such as
fprintf (stderr, format, ##__VA_ARGS__)
我想知道##
在这个宏定义中做了什么:
#define debug(M, ...) fprintf(stderr,M "\n",##__VA_ARGS __)
我用谷歌搜索了一个答案,然后得出了以下结果。
如果没有为宏提供可变参数,##
将删除逗号。所以,如果像这样调用宏
debug("message");
没有引号,扩展为
fprintf(stderr,"message");
没有
fprintf(stderr,"message",);
为什么去掉了逗号?
这是 gcc 引入的一种不可移植的语法,专门处理这种根本不传递任何参数的极端情况。 如果没有 ##,它会抱怨尾随逗号是语法错误。
https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
C++20 为此引入了 __VA_OPT__
:
https://en.cppreference.com/w/cpp/preprocessor/replace
来自 https://en.cppreference.com/w/cpp/preprocessor/replace
Note: some compilers offer an extension that allows ## to appear after a
comma and before __VA_ARGS__, in which case the ## does nothing when the
variable arguments are present, but removes the comma when the variable
arguments are not present: this makes it possible to define macros such as
fprintf (stderr, format, ##__VA_ARGS__)