#define SQR(x)x * x。意外回答 [英] #define SQR(x) x*x. Unexpected Answer
问题描述
为什么这个宏会输出144而不是121?
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);
}
推荐答案
宏有两个问题:
首先,对于参数 ++ p
,执行增量操作两次。这当然不是为了。 (作为一般的经验法则,只是不要在一行中做几件事,将它们分成更多的语句。它甚至不会在递增两次时停止:这些增量的顺序没有定义,所以没有这个操作的保证结果!
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!
第二,即使你没有 ++ p
作为参数,您的宏中仍然有一个错误!考虑输入 1 + 1
。预期输出为 4
。 1 + 1
没有副作用,所以应该很好,应该不是吗?不,因为 SQR(1 + 1)
转换为 1 + 1 * 1 + 1
$ c> 3 。
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)
$ b b
总之,你应该简单地用一个函数替换它(添加类型安全!)
Altogether, you should simply replace it by a function (to add type-safety!)
int sqr(int x)
{
return x * x;
}
您可以将其设为模板
template <typename Type>
Type sqr(Type x)
{
return x * x; // will only work on types for which there is the * operator.
}
您可以添加 constexpr
(C ++ 11),如果你计划在模板中使用一个正方形,这是有用的:
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屋!