C/C++ 关于#/##在宏定义中的用法

在C/C++的宏定义中,#/##存在特殊的作用
1. #运算符将一个宏的参数转换为字符串字面量。它仅允许出现在带参数的宏的替换列表中。
#include <cstdio> #define PRINT_STR(s) printf(#s" = %s/n", s) int main() { char *s1 = "aaa"; PRINT_STR(s1); return 0; }  
输出:
s1 = aaa
注:
printf(#s" = %s/n", s) -> printf(s1" = %s/n", s1) -> printf("s1 = %s/n", s1)->printf("s1 = %s/n", "aaa")
#s只是做宏参数字面替换
s则仍然是一个变量名
2.##运算符可以将两个记号(例如标识符)“粘”在一起,成为一个记号。(无需惊讶,##运算符被称为“记号粘合”。)
如果其中一个操作数是宏参数,“粘合”会在当形式参数被相应的实际参数替换后发生。
#include <cstdio> #define PRINT_STR(i) printf("str = %s/n", s##i) int main() { char *s1 = "s1"; char *s2 = "s2"; char *s3 = "s3"; PRINT_STR(1); PRINT_STR(2); PRINT_STR(3); return 0; }  
输出:
str = s1
str = s2
str = s3

 

3.C99的复杂宏:可变参数
#include <cstdio> #define PRINT_STR(format, ...) do{printf(format, __VA_ARGS__);}while(0) int main() { char *str1 = "s1"; char *str2 = "s2"; PRINT_STR("str1 is %s /nstr2 is %s/n",str1, str2); return 0; } 
输出:
str1 is s1 
str2 is s2
but attention!
#include <cstdio>
#define PRINT_STR(format, ...)      do{printf(format, __VA_ARGS__);}while(0)
int main() 
{ 
    char *str1 = "s1";
    char *str2 = "s2";
 
    PRINT_STR("str1 is over/n");
 
    return 0; 
}  
编译:
macro1.cpp: In function ‘int main()’:
macro1.cpp:8: error: expected primary-expression before ‘)’ token

这里提示错误,原因是少了变参列表,只有format参数,这里在format参数后就多了一个','。
so,GNU CPP想出了一个特殊的##操作,没错,##操作又来了,但是不是上面的拼接行为了。
如果可变参数被忽略或为空,“##”操作将使预处理器去除掉它前面的那个逗号。
如果在宏调用时,确实提供了一些可变参数,GNU CPP也会工作正常,它会把这些可变参数放到逗号的后面。
#include <cstdio> #define PRINT_STR(format, ...) do{printf(format, ##__VA_ARGS__);}while(0) int main() { char *str1 = "s1"; char *str2 = "s2"; PRINT_STR("str1 is over/n"); return 0; }  

输出:
str1 is over

你可能感兴趣的:(工作,function,token)