前言 使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起.
一般用法 #include #include 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; } 1 2 3 4 5 6 7 8 9 10 11
注意事项 当宏参数是另一个宏的时候,需要注意的是凡宏定义里有用’#’或’##’的地方宏参数是不会再展开. 即, 只有当前宏生效, 参数里的宏!不!会!生!效 !!!!
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 printf("%s\n", CONS(A, A)); // compile error — int(AeA) 1 2 3 4 5 两句print会被展开为:
printf(“int max: %s\n”,“INT_MAX”); printf("%s\n", int(AeA)); 1 2 分析: 由于A和INT_MAX均是宏,且作为宏CONS和STR的参数,并且宏CONS和STR中均含有#或者##符号,所以A和INT_MAX均不能被解引用。导致不符合预期的情况出现。
3.2 解决方案 解决这个问题的方法很简单. 加多一层中间转换宏. 加这层宏的用意是把所有宏的参数在这层里全部展开, 那么在转换宏里的那一个宏(_STR)就能得到正确的宏参数.
#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) // 转换宏 1 2 3 4 5 结果:
printf(“int max: %s\n”,STR(INT_MAX)); //输出为: int max:0x7fffffff //STR(INT_MAX) --> _STR(0x7fffffff) 然后再转换成字符串;
作者:flist 来源: 原文:https://blog.csdn.net/baidu_33850454/article/details/79363033 版权声明:本文为博主原创文章,转载请附上博文链接!