一些宏语句可能在C ++中有意想不到的结果? [英] some macro statements may have unexpected results in 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)
>
gets expanded to:
((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.
这篇关于一些宏语句可能在C ++中有意想不到的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!