宏定义中"#"的用法 分类: VC/MFC2011-01-09 11:32 49 人阅读 评论(0) 收藏 举报 惭愧, 今天测试了才真正明白, 在宏定义中使用"#", 还是因为群里有TX 提出, 才测试的 看代码: view plain 1. #define macro(a) #a 2. #define macro2(a,b) a##b 3. #define macro3(a,b,c) a##b##c #a, 表示a 不再是一个变量, 而变成了字符串"a" ##表示连接, a##b, 表示输入的参数名为ab, a##b##c 同理, 代表变量名为: abc 测试例子: view plain 1. int x = 3; 2. int y = 4; 3. int xy = 10; 4. int xyz=20; 5. CString str; 6. 7. 8. OutputDebugString(macro(x)); 9. 10. str.Format( "%d",macro2(x,y)); 11. OutputDebugString(str); 12. 13. str.Format( "%d",macro3(x,y,z)); 14. OutputDebugString(str); 输出结果为: x 10 20 第一个为x, marco(x), x 变成了"x"字符串 第二个为10, macro(x,y), 就是变量xy 第三个为20, macro(x,y,z), 就是变量xyz C 语言宏定义中"#","#@"和"##"的用法 一、一般用法 #把宏参数变为一个字符串,#@ 把宏参数变为一个字符,##把两个宏参数贴合在一起。 #include #include #define STR(s) #s // #与参数之间可以有空格 #define TOCHAR(c) #@c #define CONS(a,b) int(a##e##b) // ##与参数之间可以有空格 int main(void) { printf(STR(pele)); // 输出字符串"pele" printf("%c\n", TOCHAR(z)); // 输出字符z printf("%d\n", CONS(2,3)); // 2e3 输出:2000 return 0; } 二、当宏参数是另一个宏的时候 需要注意的是凡宏定义里有用'#'或'##'的地方宏参数是不会再展开的。 #define A (2) #define STR(s) #s #define CONS(a,b) int(a##e##b) printf("int max : %s\n", STR(INT_MAX)); 这行会被展开为: printf("int max : %s\n", "INT_MAX"); printf("%s\n", CONS(A, A)); 这一行被展开为: printf("%s\n", int(AeA)); INT_MAX 和A 都不会再被展开, 然而解决这个问题的方法很简单,多加一层中间转换宏。加这层宏的用意是把所有宏的参数在这层里全部展开,那么在转换宏里的那一个宏(_STR)就能得到正确的宏参数。 #define A (2) #define _STR(s) #s #define STR(s) _STR(s) // 转换宏 #define _CONS(a,b) int(a##e##b) #de...