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(,)); // 2e3 輸出:2000
return ;
}
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));
分析:
由于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) // 轉換宏
結果:
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))