#、##、__VA_ARGS__的使用

转载于:https://blog.csdn.net/auccy/article/details/88833659

使用打印信息的接口时,经常见到__VA_ARGS__和##__VA_ARGS__这两个字符串,花时间学习下这部分的知识,发现还有#和##这两个比较有意思的字符串,记下他们的用法:

#: 用来把参数转换成字符串;
例:

#include <iostream>

#define LOG(x) do { printf("%s=%d\n",#x,x); }while(0)

int main()
{
int score = 96;
LOG(score);
LOG(6);

getchar();
return 0;
}
输出:

##:用于将带参数的宏定义中将两个子串(token)联接起来,从而形成一个新的子串;但它不可以是第一个或者最后一个子串。所谓的子串(token)就是指编译器能够识别的最小语法单元;
例:

#include <iostream>

#define LOG(x) log##x()

void logA(){
printf("log func A \n");
}

void logB(){
printf("log func B\n");
}

int main()
{
LOG(A);

getchar();
return 0;
}
输出:

__VA_ARGS__:用于在宏替换部分中,表示可变参数列表;
例:

#include <iostream>

#define LOG(...) printf(__VA_ARGS__);

int main()
{
LOG("score is %d\n",96);

getchar();
return 0;
}
输出:

##__VA_ARGS__:和__VA_ARGS_作用类似;
很多博客说

##__VA_ARGS__ 宏前面加上##的作用在于,当可变参数的个数为0时,这里的##起到把前面多余的","去掉的作用,否则会编译出错

原文地址:https://www.cnblogs.com/baiduboy/p/15621344.html