前些一段时间在看WinCE的Code时发现在宏定义中有用到##,如下所示

在#define中,标准只定义了#和##两种操作。#用来把参数转换成字符串,##则用来连接两个前后两个参数,把它们变成一个字符串。
1
#define ToString(a) #a
2
ToString( A b Cd ); //A b Cd
3
ToString( A\n b Cd ); //A
4
// b Cd
5
ToString( A\ n b Cd ); //A n b Cd
6
7
8
#define ConCat(x, y) x ## y
9
ConCat( "ABC", "DEF" );
10
ConCat( 123, 4);
11
ConCat( 123.0, 5);
12
//=================================
13
// Cat( 123.0, 5.5);
14
// Cat( 'a', 'b' );
15
// Cat( "ABC", 'd' );
16
// Cat( 'a', 1234 );
17
// Cat( "ABC", 1234 );
18
//===== above can't compile =======
19
20

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

另外,在网上搜到还有一种用法:#@,把参数转换成字符
1
#define ToChar(a) #@a
2
ToChar(a); // a
3
ToChar(ab); // b
4
ToChar(abc); // c
5
ToChar(abcd); // d
6
//ToChar(abcde); // too many characters in constant
7
ToChar(1.); // .

2

3

4

5

6

7

这个没在标准上看到。上述测试是在VS studio环境下做的。不知道GCC中是否有同样的用法。