[c、c++]宏中"#"和"##"的用法(zz)
一、一般用法
我們使用#把宏參數變爲一個字符串,用##把兩個宏參數貼合在一起.
用法:
#include<cstdio>
#include<climits>
using namespace std;
#define STR(s) #s
#define CONS(a,b) int(a##e##b)
{
printf(STR(vck)); // 輸出字符串"vck"
printf("%d/n", CONS(2,3)); // 2e3 輸出:2000
return 0;
}
需要注意的是凡宏定義裏有用'#'或'##'的地方宏參數是不會再展開.
#define TOW (2)
#define MUL(a,b) (a*b)
這行的宏會被展開爲:
printf("%d*%d=%d/n", (2), (2), ((2)*(2)));
MUL裏的參數TOW會被展開爲(2).
#define A (2)
#define STR(s) #s
#define CONS(a,b) int(a##e##b)
這行會被展開爲:
printf("int max: %s/n", "INT_MAX");
這一行則是:
printf("%s/n", int(AeA));
加這層宏的用意是把所有宏的參數在這層裏全部展開, 那麼在轉換宏裏的那一個宏(_STR)就能得到正確的宏參數.
#define _STR(s) #s
#define STR(s) _STR(s) // 轉換宏
#define _CONS(a,b) int(a##e##b)
#define CONS(a,b) _CONS(a,b) // 轉換宏
輸出爲: int max: 0x7fffffff
STR(INT_MAX) --> _STR(0x7fffffff) 然後再轉換成字符串;
輸出爲:200
CONS(A, A) --> _CONS((2), (2)) --> int((2)e(2))
1、合併匿名變量名
#define ___ANONYMOUS1(type, var, line) type var##line
#define __ANONYMOUS0(type, line) ___ANONYMOUS1(type, _anonymous, line)
#define ANONYMOUS(type) __ANONYMOUS0(type, __LINE__)
例:ANONYMOUS(static int); 即: static int _anonymous70; 70表示該行行號;
第一層:ANONYMOUS(static int); --> __ANONYMOUS0(static int, __LINE__);
第二層: --> ___ANONYMOUS1(static int, _anonymous, 70);
第三層: --> static int _anonymous70;
即每次只能解開當前層的宏,所以__LINE__在第二層才能被解開;
#define FILL(a) {a, #a}
typedef struct MSG{
IDD id;
const char * msg;
}MSG;
相當於:
MSG _msg[] = {{OPEN, "OPEN"},
{CLOSE, "CLOSE"}};
#define _GET_FILE_NAME(f) #f
#define GET_FILE_NAME(f) _GET_FILE_NAME(f)
static char FILE_NAME[] = GET_FILE_NAME(__FILE__);
#define _TYPE_BUF_SIZE(type) sizeof #type
#define TYPE_BUF_SIZE(type) _TYPE_BUF_SIZE(type)
char buf[TYPE_BUF_SIZE(INT_MAX)];
--> char buf[_TYPE_BUF_SIZE(0x7fffffff)];
--> char buf[sizeof "0x7fffffff"];
這裏相當於:
char buf[11];