#define SQR(x) x*x. Unexpected Answer

前端 未结 4 788
半阙折子戏
半阙折子戏 2020-12-12 07:34

Why this macro gives output 144, instead of 121?

#include
#define SQR(x) x*x

int main()
{
    int p=10;
    std::cout<         


        
4条回答
  •  醉话见心
    2020-12-12 08:22

    The approach of squaring with this macro has two problems:

    First, for the argument ++p, the increment operation is performed twice. That's certainly not intended. (As a general rule of thumb, just don't do several things in "one line". Separate them into more statements.). It doesn't even stop at incrementing twice: The order of these increments isn't defined, so there is no guaranteed outcome of this operation!

    Second, even if you don't have ++p as the argument, there is still a bug in your macro! Consider the input 1 + 1. Expected output is 4. 1+1 has no side-effect, so it should be fine, shouldn't it? No, because SQR(1 + 1) translates to 1 + 1 * 1 + 1 which evaluates to 3.

    To at least partially fix this macro, use parentheses:

    #define SQR(x) (x) * (x)
    

    Altogether, you should simply replace it by a function (to add type-safety!)

    int sqr(int x)
    {
        return x * x;
    }
    

    You can think of making it a template

    template 
    Type sqr(Type x)
    {
       return x * x; // will only work on types for which there is the * operator.
    }
    

    and you may add a constexpr (C++11), which is useful if you ever plan on using a square in a template:

    constexpr int sqr(int x)
    {
        return x * x;
    }
    

提交回复
热议问题