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.
For example:
gets expanded to:
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: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.