8. 對(duì)“輸出格式”作宏定義,可以減少書寫麻煩。例9.3 中就采用了這種方法。
#define P printf
#define D "%d\n"
#define F "%f\n"
main(){
int a=5, c=8, e=11;
float b=3.8, d=9.7, f=21.08;
P(D F,a,b);
P(D F,c,d);
P(D F,e,f);
}
帶參宏定義
C語言允許宏帶有參數(shù)。在宏定義中的參數(shù)稱為形式參數(shù), 在宏調(diào)用中的參數(shù)稱為實(shí)際參數(shù)。對(duì)帶參數(shù)的宏,在調(diào)用中,不僅要宏展開, 而且要用實(shí)參去代換形參。
帶參宏定義的一般形式為: #define 宏名(形參表) 字符串 在字符串中含有各個(gè)形參。帶參宏調(diào)用的一般形式為: 宏名(實(shí)參表);
例如:
#define M(y) y*y+3*y /*宏定義*/
:
k=M(5); /*宏調(diào)用*/
: 在宏調(diào)用時(shí),用實(shí)參5去代替形參y, 經(jīng)預(yù)處理宏展開后的語句
為: k=5*5+3*5
#define MAX(a,b) (a>b)?a:b
main(){
int x,y,max;
printf("input two numbers: ");
scanf("%d%d",&x,&y);
max=MAX(x,y);
printf("max=%d\n",max);
}