c++ - && 的优先级高于 ||

标签 c++ c c++11

我正在读这篇文章 Precedence of && over || 。它表示,即使 && 的优先级高于 ||,我们也需要从左到右计算表达式,如果第一个表达式为 true,则不需要计算第二个表达式。 但优先级是评估的顺序,因此应首先评估所有预增量,然后应评估 (++j &&++k)。这篇文章在这一点上似乎含糊其辞。是不是?

最佳答案

来自标准

§5.14 逻辑 AND 运算符

The && operator groups left-to-right. The operands are both contextually converted to bool. 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/

相关文章:

用于原始文件流元数据的字节序感知读取的 C++ 库?

c++ - 返回抛出三元运算符?

c - 使用 UDP 套接字的多个 sendto()

c - 文件问题

c - 在顶层理解 "' const',这可能会在不提高 const 正确性的情况下降低代码可读性”

c++ - 可调整大小和动态二维数组的更好解决方案

c++ - Netbeans 讨厌 nullptr 但仍然工作正常

c++ - Code::Blocks "compile switches"在哪里?

c++ - 跳过 If 语句中的语句

c++ - 替换在模板参数推导中如何工作?