某些宏语句在 C++ 中可能会产生意想不到的结果?
哪个宏语句可能导致意外结果?
Which macro statement may cause an unexpected results ?
#define YEAR_LENGTH 365
#define MONTH_LENGTH 30
#define DAYCALC(y, m, d) ((y * YEAR_LENGTH) + (m * MONTH_LENGTH) + d)
int main()
{
int x = 5, y = 4 , z = 1;
cout << DAYCALC(x *3 , y %3 , z) << endl ;
cout << DAYCALC(x +12 , y , 300) << endl ;
cout << DAYCALC(x , 40 - y , 3+z) << endl ;
cout << DAYCALC(x , y , (z+50)) << endl ;
cout << DAYCALC(x , y %3 , z) << endl ;
cout << DAYCALC(4 % x , y++ , z) << endl;
return 0;
}
我运行程序非常好,没有任何意外结果.
I run the program very well w/o any unexpected results.
是否有一些隐藏的例外?
Are there some hidden exceptions ?
推荐答案
您遇到了运算符优先级问题.宏实际上扩展为文本复制和粘贴.
You have an operator precendence problem. Macros are literally expanded as text copy and paste.
例如:
DAYCALC(x , 40 - y , 3+z)
扩展为:
((40 - y * YEAR_LENGTH) + (x * MONTH_LENGTH) + 3+z)
请注意,由于运算符优先级,40 - y * YEAR_LENGTH
不是您想要的.
Note that 40 - y * YEAR_LENGTH
, is not what you want due to operator precedence.
所以你需要将 ()
放在宏中的参数周围:
So you need to put ()
around your parameters in the macro:
#define DAYCALC(y, m, d) (((y) * YEAR_LENGTH) + ((m) * MONTH_LENGTH) + (d))
一般来说,如果一个宏参数在宏中出现不止一次,诸如y++
(在你的最后一条语句中)之类的副作用也会被应用不止一次.所以这是需要小心的.
In general, if a macro parameter appears more than once in the macro, side effects such as y++
(in your last statement) will also be applied more than once. So it's something to be careful of.
相关文章