我正在读这篇文章 Precedence of && over || 。它表示,即使 && 的优先级高于 ||,我们也需要从左到右计算表达式,如果第一个表达式为 true,则不需要计算第二个表达式。 但优先级是评估的顺序,因此应首先评估所有预增量,然后应评估 (++j &&++k)。这篇文章在这一点上似乎含糊其辞。是不是?
最佳答案
来自标准
§5.14 逻辑 AND 运算符
The
&&
operator groups left-to-right. The operands are both contextually converted tobool
. The result is true if both operands are true and false otherwise. Unlike&
,&&
guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.The result is a
bool
. If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.
因此,在您的示例中:
(++j && ++k)
第一次评估将是
++j
然后(假设j
尚未变为0
,因此为假)
++k
然后
j && k // with both values incremented
关于c++ - && 的优先级高于 ||,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947916/