在C学习的过程的容易碰到#、##、__VA_ARGS__和##__VA_ARGS__的使用,针对这些内容进行对应的学习。
#–将其后面紧跟的符号转换为字符串
#include <stdio.h>
#define log(x) printf("%s,%d", #x, (int)x);
int main(int argc, char const *argv[])
{
int a = 10;
log(a);
return 0;
}
对应的输出结果表示为:
./a.out
a,10zms@SH-5CD227B86G
## 用于将带参数的宏定义中将两个子串(token)联接起来,从而形成一个新的子串;但它不可以是第一个或者最后一个子串。所谓的子串(token)就是指编译器能够识别的最小语法单元
#include <stdio.h>
#define LOG(X) log##X();
void logA(){
printf("log func A");
}
void logB(){
printf("log func B");
}
int main(int argc, char const *argv[])
{
LOG(A);
return 0;
}
对应的输出的结果为:
~/learn/learn_cpp$ ./a.out
log func A
__VA_ARGS__操作—表示该部分允许输入可变参数
#include <stdio.h>
#define PR(...) printf(__VA_ARGS__)
int main()
{
int wt=1,sp=2;
PR("hello\n");
PR("weight = %d, shipping = %d\n",wt,sp);
return 0;
}
对应的输出的结果为:
$ ./a.out
hello
weight = 1, shipping = 2
##VA_ARGS–支持可变参数的输入或者无参数输入
#include <stdio.h>
#define debug(format, args...) printf(format, ##args)
int main(int argc, char const *argv[])
{
int year = 2018;
debug("hello, world\n");
debug("year: %d\n", year);
debug("year year d\n");
return 0;
}
输出为:
$ ./a.out
hello, world
year: 2018
year year d