现在的位置: 首页 > 综合 > 正文

宏定义的细节问题

2019年08月12日 ⁄ 综合 ⁄ 共 436字 ⁄ 字号 评论关闭

示例代码:

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

抱歉!评论已关闭.