宏定義的細節問題

示例代碼:

#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);
}




發佈了116 篇原創文章 · 獲贊 49 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章