?!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
使用预处理的二大原因Q?br style="margin: 0px; padding: 0px;"/>
1Q由于写E序时可能将某个特定数量在程序中出现的所有实例统l加以修攏V我们希望能够通过E序中只改动一处数|然后重新~译可以实现。预处理器可以做到这一炏V?/strong>
2 Q大多数C语言实现在函数调用时都会带来重大的系l开销?/strong>因此Q我们也许希望有q样一U程序块Q它看上d一个函敎ͼ但却没有函数调用的开销。D例来说getchar,putchar l常被实Cؓ宏,以避免在每次执行输入或输Z个字W这L单的操作Ӟ都要调用相应的函数而造成pȝ效率的下降?/p> 预处理器指o?号开始,到其后第一个换行符为止。预处理器不q行计算Q它只是按照指oq行文字替换操作 带参数的?/strong>
#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;
}
l果Q?The value =-5
The value =3
The value =3
The value =2
#q算W?/strong>
#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;
}
l果Q?The square of y is 25
The square of 2+4 is 36
可变宏:... 和__VA_ARGS__
#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
l果Q?
Message 1:X=48
Message 2:X=48.00,y=6.9282
注意Q省略号只能代替最后的参数?/pre>
预定义宏
#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__);
}
l果Q?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.