标签:
[c、c++]宏中"#"和"##"的用法(zz)
#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; }
#define TOW (2) #define MUL(a,b) (a*b) printf("%d*%d=%d/n", TOW, TOW, MUL(TOW,TOW));
printf("%d*%d=%d/n", (2), (2), ((2)*(2)));
#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 #i nclude<climits>
printf("int max: %s/n", "INT_MAX"); printf("%s/n", CONS(A, A)); // compile error
这一行则是:
printf("%s/n", int(AeA));
#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,int型的最大值,为一个变量 #i nclude<climits> 输出为: 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))
#define ___ANONYMOUS1(type, var, line) type var##line #define __ANONYMOUS0(type, line) ___ANONYMOUS1(type, _anonymous, line) #define ANONYMOUS(type) __ANONYMOUS0(type, __LINE__)
#define FILL(a) {a, #a} enum IDD{OPEN, CLOSE}; typedef struct MSG{ IDD id; const char * msg; }MSG; MSG _msg[] = {FILL(OPEN), FILL(CLOSE)}; 相当于: 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"];
标签:
原文地址:http://www.cnblogs.com/shihaochangeworld/p/5814212.html