define 中的# ## 一般是用来拼接字符串的,但是实际使用过程中,有哪些细微的差别呢,我们通过几个例子来看看。
#是字符串化的意思,出现在宏定义中的#是把跟在后面的参数转成一个字符串;
#define ENUM_to_String(enum_id) #enum_id
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; } |
id="iframe_0.24500557948733026" src="data:text/html;charset=utf8,%3Cimg%20id=%22img%22%20src=%22http://a.hiphotos.baidu.com/album/pic/item/2fdda3cc7cd98d1081fdc3df213fb80e7bec9037.jpg?_=3463080%22%20style=%22border:none;max-width:999px%22%3E%3Cscript%3Ewindow.onload%20=%20function%20()%20%7Bvar%20img%20=%20document.getElementById('img');%20window.parent.postMessage(%7BiframeId:'iframe_0.24500557948733026',width:img.width,height:img.height%7D,%20'http://www.cnblogs.com');%7D%3C/script%3E" frameborder="0" scrolling="no" style="margin: 0px; padding: 0px; border-width: initial; border-style: none; width: 991px; height: 660px;">
去掉#号我们得到这样的结果,直接把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; } |
id="iframe_0.5359436411709109" src="data:text/html;charset=utf8,%3Cimg%20id=%22img%22%20src=%22http://a.hiphotos.baidu.com/album/pic/item/2cf5e0fe9925bc31fc2ace765edf8db1ca1370ed.jpg?_=3463080%22%20style=%22border:none;max-width:999px%22%3E%3Cscript%3Ewindow.onload%20=%20function%20()%20%7Bvar%20img%20=%20document.getElementById('img');%20window.parent.postMessage(%7BiframeId:'iframe_0.5359436411709109',width:img.width,height:img.height%7D,%20'http://www.cnblogs.com');%7D%3C/script%3E" frameborder="0" scrolling="no" style="margin: 0px; padding: 0px; border-width: initial; border-style: none; width: 958px; height: 602px;">