C++/C 宏定义(define)中# ## 的含义(转)

http://hi.baidu.com/kiraversace/item/1148ee057147981a4ac4a3e9

C++/C 宏定义(define)中# ## 的含义

define 中的# ## 一般是用来拼接字符串的,但是实际使用过程中,有哪些细微的差别呢,我们通过几个例子来看看。

#是字符串化的意思,出现在宏定义中的#是把跟在后面的参数转成一个字符串;

eg:

1
2
3
#define  strcpy__(dst, src)      strcpy(dst, #src)
     
strcpy__(buff,abc)  相当于 strcpy__(buff,“abc”)

##是连接符号,把参数连接在一起

1
2
3
#define FUN(arg)     my##arg
则     FUN(ABC)
等价于  myABC

再看一个具体的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
         
using namespace std;
         
#define  OUTPUT(A) cout<<#A<<":"<<(A)<<endl;
         
int main()
{
    int a=1,b=2;
         
    OUTPUT(a);
    OUTPUT(b);
    OUTPUT(a+b);
         
    return 1;
}

 

去掉#号我们得到这样的结果,直接把a,b的值打印出来了,这是符合语法规则的,所以#的作用显而易见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
        
using namespace std;
        
#define  OUTPUT(A) cout<<A<<":"<<(A)<<endl;
        
int main()
{
    int a=1,b=2;
        
    OUTPUT(a);
    OUTPUT(b);
    OUTPUT(a+b);
        
    return 1;
}

 

posted @ 2013-12-07 18:47  LittleAnt  阅读(46098)  评论(0编辑  收藏  举报