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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM