【问题标题】:The order of evaluation of equality operator in C++C++中相等运算符的求值顺序
【发布时间】:2015-02-04 06:03:57
【问题描述】:

最近我读了一些章节 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?它是否涉及相等运算符的评估顺序?

正如书中所说,只有四个运算符保证顺序,不包括相等运算符。所以上面表达式的结果应该是未定义的,对吗?如果不是,应该是什么?

期待您的回复。提前致谢。

【问题讨论】:

  • 这个和C++语言的定义有关。研究C++11 规范(即阅读最新草案n3337 ....)
  • 你混淆了两个非常不同的东西。 true 被转换为另一个参数的类型,因为在算术运算符中,较低等级的参数被转换为另一个参数的类型。与求值顺序无关。
  • 如前所述(即脱离上下文),“如果 val 不是 bool,则在应用 == 运算符之前将 true 转换为 val 的类型。” 一般来说不正确,因为val 可能是具有operator bool() const 成员的类的实例,然后将与true 进行比较,而不涉及任何整数转换。

标签: c++ equality operator-precedence


【解决方案1】:

它与评估的顺序无关。比较运算符总是对其操作数执行通常的算术转换。这些转换同样适用于两个操作数(尽管未指定顺序)。在将bool 与另一个整数类型进行比较的情况下,bool 类型的操作数总是首先提升为int

【讨论】:

    【解决方案2】:

    ==、

    运算符的哪一侧转换为什么以及以什么顺序有点深奥,并且会涉及编译器编写者。这超出了程序员的范围。

    【讨论】:

      【解决方案3】:

      if 语句的条件有两种不同的类型 它们是:

      1. int
      2. 布尔

      在 c++ 中的类型如:

      1. 布尔
      2. 字符

      总是首先转换为 int,因此在 if 的条件下,bool 的 true 被转换为 int 并且为 1,即 true 为 1 并且 val 保持不变。

      【讨论】:

        猜你喜欢
        • 2021-07-12
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 2012-01-07
        • 2015-03-12
        • 2014-08-18
        • 1970-01-01
        • 2021-05-18
        相关资源
        最近更新 更多