1. 前言https://blog.csdn.net/baidu_33850454/article/details/79363033 使用#把宏參數(shù)變?yōu)橐粋€字符串,用##把兩個宏參數(shù)貼合在一起. 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. 注意事項當宏參數(shù)是另一個宏的時候,需要注意的是凡宏定義里有用’#’或’##’的地方宏參數(shù)是不會再展開.
即, 只有當前宏生效, 參數(shù)里的宏!不!會!生!效 ?。。?!
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)); 分析: 由于A和INT_MAX均是宏,且作為宏CONS和STR的參數(shù),并且宏CONS和STR中均含有#或者##符號,所以A和INT_MAX均不能被解引用。導致不符合預期的情況出現(xiàn)。 3.2 解決方案解決這個問題的方法很簡單. 加多一層中間轉(zhuǎn)換宏. 加這層宏的用意是把所有宏的參數(shù)在這層里全部展開,
那么在轉(zhuǎn)換宏里的那一個宏(_STR)就能得到正確的宏參數(shù).
#define A (2)
#define _STR(s) #s
#define STR(s) _STR(s) // 轉(zhuǎn)換宏
#define _CONS(a,b) int(a##e##b)
#define CONS(a,b) _CONS(a,b) // 轉(zhuǎn)換宏 結(jié)果: printf("int max: %s\n",STR(INT_MAX));
//輸出為: int max:0x7fffffff
//STR(INT_MAX) --> _STR(0x7fffffff) 然后再轉(zhuǎn)換成字符串;
printf("%d\n", CONS(A, A));
//輸出為:200
//CONS(A, A) --> _CONS((2), (2)) --> int((2)e(2))
|