爲什麼max(0,1)
在此程序中的行爲與max(1,0)
不同?與括號一起使用時宏變化的行爲
#define max(a,b) ((a)>(b))?(a):(b)
int main()
{
printf("max(0,1) = %d \n",max(0,1));
printf("max(0,1)+1 = %d \n",max(0,1)+1);
printf("max(0,1)+2 = %d \n",max(0,1)+2);
printf("max(1,0) = %d \n",max(1,0));
printf("max(1,0)+1 = %d \n",(max(1,0)+1));
printf("max(1,0)+2 = %d \n",(max(1,0)+2));
return 0;
}
輸出:
max(0,1) = 1
max(0,1)+1 = 2
max(0,1)+2 = 3
max(0,1) = 1
max(1,0)+1= 1
max(1,0)+2= 1
爲什麼做這些表現良好,如果使用一個額外的括號?
#define max(a,b) (((a)>(b))?(a):(b))
想想擴張的結果:'MAX(0,1)+ 1' =>'(( 0)>(1))→(0):(1)+ 1'這相當於'(0> 1)? ((0)>(1))→(0):(1))+ 1「的情況下,與第一種情況下的」0:(1 + 1) 0:1)+ 1'。 – Dirk
另請參閱http://stackoverflow.com/questions/5812877/why-one-needs-two-brackets-to-use-macros-in-c-c – doctorlove