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))