| 網(wǎng)站首頁 | 關(guān)于我們 | 開發(fā)優(yōu)勢 | 產(chǎn)品展示 |
| 合作企業(yè) | 新聞動態(tài) | 聯(lián)系我們 | 電話聯(lián)系 |
文章作者:濟(jì)南軟件開發(fā) 時間:2016年12月20日
使用預(yù)處理的二大原因:
1,由于寫程序時可能將某個特定數(shù)量在程序中出現(xiàn)的所有實(shí)例統(tǒng)統(tǒng)加以修改。我們希望能夠通過程序中只改動一處數(shù)值,然后重新編譯就可以實(shí)現(xiàn)。預(yù)處理器可以做到這一點(diǎn)。
2 ,大多數(shù)C語言實(shí)現(xiàn)在函數(shù)調(diào)用時都會帶來重大的系統(tǒng)開銷。因此,我們也許希望有這樣一種程序塊,它看上去像一個函數(shù),但卻沒有函數(shù)調(diào)用的開銷。舉例來說getchar,putchar 經(jīng)常被實(shí)現(xiàn)為宏,以避免在每次執(zhí)行輸入或輸出一個字符這樣簡單的操作時,都要調(diào)用相應(yīng)的函數(shù)而造成系統(tǒng)效率的下降。
預(yù)處理器指令從#號開始,到其后第一個換行符為止。預(yù)處理器不進(jìn)行計(jì)算,它只是按照指令進(jìn)行文字替換操作
帶參數(shù)的宏
#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;
}
結(jié)果:
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;
}
結(jié)果:
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
結(jié)果:
Message 1:X=48
Message 2:X=48.00,y=6.9282
注意:省略號只能代替最后的參數(shù)。#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__);
}
結(jié)果:
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.想要了解更多詳情歡迎來電咨詢18678812288
登陸網(wǎng)址:m.h6244.cn。
聯(lián)系人:王經(jīng)理。