我想知道在这个宏定义中,##
是什么意思:
#define debug(M, ...) fprintf(stderr,M "\n",##__VA_ARGS __)
我谷歌搜索了一个答案,我找到了以下内容。
##
在没有变量参数的情况下将删除逗号。 因此,如果像这样调用宏
debug("message");
没有引号时,它会被扩展为
fprintf(stderr,"message");
不。fprintf(stderr,"message",);
为什么要去掉逗号?
我想知道在这个宏定义中,##
是什么意思:
#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
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__)