[basic c++]c中的宏重复展开
2018-07-09 本文已影响28人
Quasars
c中的宏重复展开
-
宏中的
#和##-
#字符串化: #abc ---> "abc" -
##拼接: a##b ---> ab
-
-
替换规则:
-
一般情况下,预处理器会对替换表中的宏符号进行重复扫描,直到所有宏符号都被展开为止;
-
遇到2种情况不展开:
- 某个宏展开后的列表中存在它自己,则该符号不重复展开;
-
#开头的宏不重复展开.
-
上述2个在实际中的做法有,如果某个宏以#开头(宏1),但有可能其参是另一个宏(宏2),需要先展开该宏,需要用1个胶水宏(宏3)包裹宏1,否则宏2将无法正常展开, 看以下代码片段。
-
1 #include <cstdio>
2
3 #define H0 "a0"
4 #define H1 "b0"
5 #define H2 "c0"
6
7 #define GetH(x) H##x
8
9 #define STR(x) #x
10 #define STRHELPER(x) STR(x)
11 #define CONCAT(a,b) a##b
12
13
14 int test1() {
15 printf("%s\n", GetH(0)); // compiler will repeat scaning for macro targets.
16 return 0;
17 }
18
19
20 int test2() {
21 printf("%s\n", STR(CONCAT(I,PAD))); // directly call STR, output: CONCAT(I,PAD)
22 printf("%s\n", STRHELPER(CONCAT(I,PAD))); // call the helper macro, output: IPAD
23 return 0;
24 }
25
26
27 int main() {
28 test2();
29 return 0;
30 }