c++ - c++ 标准是否指定了运算符&&(内置)的评估顺序?

标签 c++ logical-operators operator-precedence expression-evaluation

这个问题在这里已经有了答案:





Is short-circuiting logical operators mandated? And evaluation order?

(7 个回答)


2年前关闭。




我总是不敢这样编码:

void func( some_struct* ptr ) {
    if ( ptr != nullptr && ptr->errorno == 0 )
        do something...
};

相反,我总是这样做:
void func( some_struct* ptr ) {
    if ( ptr != nullptr )
        if ( ptr->errorno == 0 )
            do something...
};

因为我担心逻辑运算符 && 的评估顺序在 C++ 标准中是未指定的,即使通常我们可以使用几乎所有当今的编译器得到正确的结果。
a book , 2 条规则让我想确切地了解它。

我的问题是:
不重载,是逻辑运算符“&&”和“||”的求值顺序定?

对不起我丑陋的英语,我是中国人。如果有重复的主题,我深表歉意,因为我无法找出正确的关键字来搜索。
不管怎么说,还是要谢谢你!

最佳答案

是的,标准保证内置逻辑 AND 运算符和逻辑 OR 运算符。

(强调我的)

[expr.log.and]/1

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.



[expr.log.or]/1

The || operator groups left-to-right. The operands are both contextually converted to bool. The result is true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

关于c++ - c++ 标准是否指定了运算符&&(内置)的评估顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897454/

相关文章:

java - a = (a++) * (a++) 在 Java 中给出奇怪的结果

c++ - 如何从包含空格的文件中读取字符串 C++

java - java 中的逻辑运算符(使用 Struts 1 的验证)

C++ 类成员的循环引用

java - Java 是否检查 "&&"(和)运算符中的所有参数,即使其中一个参数为假?

javascript - 谁能解释一下 jCarousel 中的以下 JavaScript 代码?

javascript - 为什么在这段 JavaScript 代码中函数调用发生在变量 x 递增之后

c语言复合赋值,v += e和v = v + e有什么区别?

c++ - 是否可以使用带有立方贴图颜色附件的深度渲染缓冲区?

c++ - 如何使用几何着色器从点数据绘制正方形