Problem with Macros

后端 未结 4 1088
轻奢々
轻奢々 2020-12-06 13:40

HI ,

Can some one help me in understanding why the value of SQUARE(x) is 49 ?

I am using Visual C++ 6.0 .

#define SQUARE(X) X * X

int main(i         


        
4条回答
  •  渐次进展
    2020-12-06 14:06

    Neil Butterworth, Mark and Pavel are right.

    SQUARE(++y) expands to ++y * ++y, which increments twice the value of y.

    Another problem you could encounter: SQUARE(a + b) expands to a + b * a + b which is not (a+b)*(a+b) but a + (b * a) + b. You should take care of adding parentheses around elements when needed while defining macros: #define SQUARE(X) ((X) * (X)) is a bit less risky. (Ian Kemp wrote it first in his comment)

    You could instead use an inline template function (no less efficient at runtime) like this one:

    template 
    inline T square(T value)
    {
        return value*value;
    }
    

    You can check it works:

    int i = 2;
    std::cout << square(++i) << " should be 9" << std::endl;
    std::cout << square(++i) << " should be 16" << std::endl;
    

    (no need to write

    square(++i)
    

    because the int type is implicit for i)

提交回复
热议问题