#define SQR(x) x*x.意外的答案

2022-01-11 00:00:00 macros c++

Why this macro gives output 144, instead of 121?

#include<iostream>
#define SQR(x) x*x

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

解决方案

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 <typename Type>
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;
}

相关文章