示例代碼:
#define PERIMTER(X,Y) 2*X+2*Y
int main()
{
int length = 5;
int width = 2;
int high = 8;
int result = 0;
result = PERIMTER(length,width)*high;
printf("result = %d \n" , result);
}
問題分析:
上述代碼是實現計算長方體體積,先通過宏計算出矩形周長,再乘以高。但實際結果爲42,計算錯誤,原因是,宏定義只是文本替換,替換後的語句爲:
result = 2*length + 2*width*high;
因此,用於表達式的宏,最好在定義時在整體語句上加個括號。
正確代碼:
#define PERIMTER(X,Y) (2*X+2*Y)
int main()
{
int length = 5;
int width = 2;
int high = 8;
int result = 0;
result = PERIMTER(length,width)*high;
printf("result = %d \n" , result);
}