最近看了一些C++ Primer的章节,有一点让我很困惑。
书上说:
There are four operators that do guarantee the order in which operands are evaluated.
the logical AND (&&) operator,
the logical OR (||) operator,
the conditional (? :) operator,
and the comma (,) operator.
然后我看到了这些代码:
if (val == true) { /* ... */ } // true only if val is equal to 1!
然后书中解释:
If val is not a bool, then true is converted to the type of val before the == operator is applied.
That is, when val is not a bool, it is as if we had written
if (val == 1) { /* ... */ }
这是我的问题:
为什么bool类型true转为算术类型,而不是val?是否涉及相等运算符的求值顺序?
正如书上所说只有四个运算符保证顺序,不包括相等运算符。所以上面表达式的结果应该是未定义的,对吗?如果不是,它应该是什么?
期待您的回复。提前致谢。
最佳答案
与求值顺序无关。比较运算符总是对其操作数执行通常的算术转换。这些转换同样适用于两个操作数(尽管未指定顺序)。在 bool
的情况下正在与另一个整数类型进行比较,类型为 bool
的操作数始终提升为 int
首先。
关于c++ - C++中相等运算符的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28314518/