#define SQR(x) x*x.意外的答案 [英] #define SQR(x) x*x. Unexpected Answer

查看:11
本文介绍了#define SQR(x) x*x.意外的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于#define SQR(x) x*x.意外的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆