Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have an operator precendence problem. Macros are literally expanded as text copy and paste.

For example:

DAYCALC(x , 40 - y , 3+z)

gets expanded to:

((40 - y * YEAR_LENGTH) + (x * MONTH_LENGTH) + 3+z)

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))

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...