使用預處理的二大原因:1是,由於寫程序時可能將某個特定數量在程序中出現的所有實例統統加以修改。我們希望能夠通過程序中只改動一處數值,然後重新編譯就可以實現。預處理器可以做到這一點。
2 大多數C語言實現在函數調用時都會帶來重大的系統開銷。因此,我們也許希望有這樣一種程序塊,它看上去像一個函數,但卻沒有函數調用的開銷。舉例來說getchar,putchar 經常被實現為宏,以避免在每次執行輸入或輸出一個字符這樣簡單的操作時,都要調用相應的函數而造成系統效率的下降。
預處理器指令從#號開始,到其後第一個換行符為止。預處理器不進行計算,它只是按照指令進行文字替換操作
帶參數的宏
#include#define ABS(x) x>0?x:-x #define ABS1(x) (x)>0?(x):-(x) #define ABS2(x) ((x)>0?(x):-(x)) int main(void) { int a=1; int b=4; printf("The value =%d \n",ABS(a-b)); printf("The value =%d \n",ABS1(a-b)); int c =4; int d=1; printf("The value =%d \n",ABS1(c-d)-1); printf("The value =%d \n",ABS2(c-d)-1); return 0; } 結果: The value =-5 The value =3 The value =3 The value =2
#include#define PSQR(x) printf("The square of "#x" is %d \n",((x)*(x))) int main(void) { int y =5; PSQR(y); PSQR(2+4); return 0; } 結果: The square of y is 25 The square of 2+4 is 36
#include#include #define PR(X,...) printf("Message " #X":"__VA_ARGS__) int main(void) { double x =48; double y; y=sqrt(x); PR(1,"X=%g\n",x); PR(2,"X=%.2f,y=%.4f\n",x,y); return 0; } 編譯時: Gcc variadic.c –lm 結果: Message 1:X=48 Message 2:X=48.00,y=6.9282 注意:省略號只能代替最後的參數。
#includevoid why_me(); int main(void) { printf("The file is %s.\n",__FILE__); printf("The date is %s.\n",__DATE__); printf("The time is %s.\n",__TIME__); //printf("The version is %ld.\n",__STDC_VERSION__); printf("This is line %d.\n",__LINE__); printf("This function is %s\n",__func__); why_me(); return 0; } void why_me() { printf("This function is %s.\n",__func__); printf("This is line %d.\n",__LINE__); } 結果: The file is predef.c. The date is Dec 13 2013. The time is 22:52:07. This is line 10. This function is main This function is why_me. This is line 18.