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

 

相關文章
相關標籤/搜索