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

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

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

define 中的# ## 通常是用来拼接字符串的,可是实际使用过程当中,有哪些细微的差异呢,咱们经过几个例子来看看。ios

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

eg:code

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

##是链接符号,把参数链接在一块儿blog

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

再看一个具体的例子ci

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;
}

 

相关文章
相关标签/搜索