1. 前言 使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起.
2. 一般用法 #include<cstdio> #include<climits> using namespace std; #define STR(s) #s #define CONS(a,b) int(a##e##b) int main() { printf(STR(vck)); // 输出字符串"vck" printf("%d\n", CONS(2,3)); // 2e3 输出:2000 return 0; } 3. 注意事项 当宏参数是另一个宏的时候,需要注意的是凡宏定义里有用’#’或’##’的地方宏参数是不会再展开. 即, 只有当前宏生效, 参数里的宏!不!会!生!效 !!!!
3.1 举例 #define A (2) #define STR(s) #s #define CONS(a,b) int(a##e##b) printf("int max: %s\n", STR(INT_MAX)); // INT_MAX #include<climits> printf("%s\n", CONS(A, A)); // compile error --- int(AeA) 两句print会被展开为:
printf("int max: %s\n","INT_MAX"); printf("%s\n", int(AeA));
3.2 解决方案 解决这个问题的方法很简单. 加多一层中间转换宏. 加这层宏的用意是把所有宏的参数在这层里全部展开,
#define A (2) #define _STR(s) #s #define STR(s) _STR(s) // 转换宏 #define _CONS(a,b) int(a##e##b) #define CONS(a,b) _CONS(a,b) // 转换宏 结果:
printf("int max: %s\n",STR(INT_MAX)); //输出为: int max:0x7fffffff //STR(INT_MAX) --> _STR(0x7fffffff) 然后再转换成字符串;
printf("%d\n", CONS(A, A)); //输出为:200 //CONS(A, A) --> _CONS((2), (2)) --> int((2)e(2))