2016年7月22日 星期五

#define 簡單心得記錄


用過C語言的人都知道 #define 是用來定義巨集(macro),基本用法如下

#define PI 3.14159

這樣在程式碼中如果有出現 "PI"這個字的話compiler都會自動轉成3.14159。


#define也可用來定義函式,範例如下

#define getmax(a,b) a>b?a:b




如果在#define裡面#及##有特殊的用法,#會將接在後面的參數轉成string。
##則是會將2個參數串接在一起,用以下範例說明。

Example 1:
#define str(x) #x
cout << str(test);


cout << str(test); 會被轉成 cout << "test";


Example 2:
#define glue(a,b) a ## b
glue(c,out) << "test";


glue(c,out) << "test";會被轉成 cout << "test"

沒有留言:

張貼留言