c语言宏嵌套和展开规则
生活随笔
收集整理的這篇文章主要介紹了
c语言宏嵌套和展开规则
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
基本原則:
在展開(kāi)當(dāng)前宏函數(shù)時(shí),如果形參有#或##則不進(jìn)行宏參數(shù)的展開(kāi),否則先展開(kāi)宏參數(shù),再展開(kāi)當(dāng)前宏。
#是在定義兩邊加上雙引號(hào)
#define _TOSTR(s) #sprintf(_TOSTR(test ABC))
printf(_TOSTR("test ABC"));
printf(_TOSTR(_TOSTR(test ABC)));==================
預(yù)編譯結(jié)果:
printf("test ABC")
printf("\"test ABC\"");
printf("_TOSTR(test ABC)");
##是原樣代入
?
#define HI_BOY HiBoy!
#define __ORIGINAL(s) s
#define _TOSTR(s) #s
#define STR_CONCAT(x, y) x##yprintf(HI_BOY);
printf(__ORIGINAL(HI_BOY));
printf(_TOSTR(HI_BOY));
printf(_TOSTR(__ORIGINAL(HI_BOY)));
printf(STR_CONCAT(HI_BOY, HI_BOY ));
printf(STR_CONCAT(_TOSTR(HI_BOY), _TOSTR(HI_BOY) ));
===========================================================
預(yù)處理后的結(jié)果:
printf(HiBoy!);
printf(HiBoy!);
printf("HI_BOY");
printf("__ORIGINAL(HI_BOY)");
printf(HI_BOYHI_BOY);
printf("HI_BOY" "HI_BOY");
連續(xù)的兩個(gè)雙引號(hào)會(huì)被忽略掉
以下寫法結(jié)果一樣:
printf("this is a test sentence. are you ok?\n");
printf("this is a test ""sentence."" are you ok?\n");
printf("this is a test sentence." " are you ok?\n");
printf("this is a" " test ""sentence. are"" you ok?\n");==============
this is a test sentence. are you ok?
this is a test sentence. are you ok?
this is a test sentence. are you ok?
this is a test sentence. are you ok?
嵌套
#define QUOTATION "
#define HI_BOY HiBoy!
#define __ORIGINAL(s) s
#define _TOSTR(s) #s
#define STR_CONCAT(x, y) x##yprintf(HI_BOY);
printf(__ORIGINAL(HI_BOY));
printf(_TOSTR(HI_BOY));
printf(_TOSTR(__ORIGINAL(HI_BOY)));
printf(STR_CONCAT(HI_BOY, HI_BOY ));
printf(STR_CONCAT( _TOSTR(HI_BOY), _TOSTR(HI_BOY) ));
printf( STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ));
printf( _TOSTR(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) )));
printf(_TOSTR(__ORIGINAL(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ))));
printf( ""(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ))"");
printf(_TOSTR(__ORIGINAL(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ))));
printf( QUOTATION(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ))QUOTATION);
printf( QUOTATION STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) )QUOTATION);==================================================
預(yù)編譯結(jié)果:
printf(HiBoy!);
printf(HiBoy!);
printf("HI_BOY");
printf("__ORIGINAL(HI_BOY)");
printf(HI_BOYHI_BOY);
printf("HI_BOY" "HI_BOY");
printf( HiBoy!HiBoy!);
printf( "STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) )");
printf("__ORIGINAL(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ))");
printf( ""(HiBoy!HiBoy!)"");
printf("__ORIGINAL(STR_CONCAT( __ORIGINAL(HI_BOY), __ORIGINAL(HI_BOY) ))");
printf( "(HiBoy!HiBoy!)");
printf( " HiBoy!HiBoy! ");
總結(jié)
以上是生活随笔為你收集整理的c语言宏嵌套和展开规则的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 黄山风景区入口有几个
- 下一篇: emacs快捷键