枚举型变为字符串(宏#)

来源:互联网 发布:厦门安全网络教育平台 编辑:程序博客网 时间:2024/05/22 00:39

枚举型变为字符串(宏#)

 
转载
有必要先讲一下宏#,当然可以直接调到第4点看结果
1. 宏中"#"
#把宏参数变为一个字符串
#define STR(s)     #s
printf(STR(vck));           // 输出字符串"vck"

2. "##"的用法
#define CONS(a,b)  int(a##e##b)
int 2e3=2000;
printf("%d\n", CONS(2,3));  // 2e3 输出:2000

3. 当宏参数是另一个宏的时候

a. 需要注意的是凡宏定义里有用"#"或"##"的地方宏参数是不会再展开.
#define A          (2)
#define STR(s)     #s
#define CONS(a,b)  int(a##e##b)
printf("%s\n", CONS(A, A));               // compile error
这一行则是:
printf("%s\n", int(AeA));

b. 解决这个问题的方法很简单:加多一层中间转换宏
#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型的最大值,为一个变量#include
输出为: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))

注:VC6对(2)e(2)报错,将A的定义改成2即可

4. 枚举型变为字符串
#define NAME(a) _T(#a)
0 0
原创粉丝点击