一个宏定义值得注意的地方

来源:互联网 发布:移动网络想玩传奇 编辑:程序博客网 时间:2024/04/25 06:16

下面一段宏定义:

#include<iostream>
using namespace std;
#define MAX(x,y) (x)>(y)?(x):(y)
int _tmain(int argc, _TCHAR* argv[])
{
 int a=5,b=2,c=3,d=3,t;
 t=MAX(a+b,c+d)*10;
 printf("%d/n",t);
 system("pause");
 return 0;
}

打印结果:7//问题.......不应该是70吗?

分析:使用替换的方法看看 t=MAX(a+b,c+d)*10;到底是什么:

t = (a+b)>(c+d)?(a+b):(c+d)*10

原来最后的10乘了(c+d)

改进后

#include<iostream>
using namespace std;
#define MAX(x,y) ((x)>(y)?(x):(y))//注意括号
int _tmain(int argc, _TCHAR* argv[])
{
 int a=5,b=2,c=3,d=3,t;
 t=MAX(a+b,c+d)*10;
 printf("%d/n",t);
 system("pause");
 return 0;
}

 打印结果 70

原创粉丝点击