在刘先生所著的《面向对象程序设计》中提到,由于#define预处理器没有较好的检查机制,使得在预处理语句中的宏定义会存在程序瑕疵,书中所举列子如下:
#include <iostream>
using namespace std;
#define MAX(x, y) ((x) > (y)) ? (x) : (y)
void main()
{
int a(7), b(0), c, d;
cout << " (1) a = " << a << " , b = " << b << endl;
c = MAX(++a, b);
cout << " (2) a = " << a << " , b = " << b << " , max = " << c << endl;
d = MAX(++a, b + 12);
cout << " (3) a = " << a << " , b = " << b << " , max = " << d << endl;
getchar();
}
此代码运行的结果是:
显然在MAX(++a, b);处把a加了两次,而在 MAX(++a, b + 12);处a只加了一此,为什么会这样?
经过认真阅读代码,发现第一处使用MAX时,++a是大于b的,即x>y,那么最后的返回值还是++a,由于预处理器没有完善的检查机制,使得a再加一次,而第二次则是b+12大,所以++a只执行了一次。为了验证此想法,修改代码如下:
#include <iostream>
using namespace std;
#define MAX(x, y) ((x) > (y)) ? (x) : (y)
void main()
{
int a(7), b(0), c, d;
cout << " (1) a = " << a << " , b = " << b << endl;
c = MAX(++a, b);
cout << " (2) a = " << a << " , b = " << b << " , max = " << c << endl;
d = MAX(++a, b + 7);
cout << " (3) a = " << a << " , b = " << b << " , max = " << d << endl;
getchar();
}
运行结果如下:
由于++a = 8,b + 7 = 7,所以x > y,使得++a又执行了两次。
另外,书中给出的采用内联函数的解决方案如下:
#include <iostream>
using namespace std;
inline int max( int x, int y )
{ return x > y ? x : y; }
void main()
{
int a(7), b(0), c, d;
cout << " (1) a = " << a << " , b = " << b << endl;
c = max(++a, b);
cout << " (2) a = " << a << " , b = " << b << " , max = " << c << endl;
d = max(++a, b + 12);
cout << " (3) a = " << a << " , b = " << b << " , max = " << d << endl;
getchar();
}