首页 > 其他 > 详细

宏定义详细信息

时间:2015-10-26 11:47:17      阅读:225      评论:0      收藏:0      [点我收藏+]

演示示例代码:

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




版权声明:本文博主原创文章,博客,未经同意不得转载。

宏定义详细信息

原文:http://www.cnblogs.com/bhlsheji/p/4910541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!