Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...