错误示例:
#define mylog(format, ...) printf("mylog:" format "\n", __VA_ARGS__)
int main()
{
/**
* 此处会报错
* 因为展开之后为:printf("mylog:" "hello world!" "\n", )
* 多了一个逗号','所以会报错
*/
mylog("hello world!");
return 0;
}
修改如下:
#define mylog(format, ...) printf("mylog:" format "\n", ##__VA_ARGS__)
int main()
{
/**
* 此处不会报错
* 因为展开之后为:printf("mylog:" "hello world!" "\n")
* 如果可变参数个数为0个时,mylog宏展开时,##__VA_ARGS__会将前面的逗号去掉
*/
mylog("hello world!");
return 0;
}