c++ - 是否强制要求短路逻辑运算符?和评价顺序?

标签 c++ c logical-operators short-circuiting operator-precedence

ANSI 标准是否强制在 C 或 C++ 中将逻辑运算符短路?

我很困惑,因为我记得 K&R 书中说你的代码不应该依赖于这些被短路的操作,因为它们可能不会。有人可以指出标准中哪里说逻辑操作总是短路吗?我最感兴趣的是 C++,C 的答案也很棒。

我还记得读过(不记得在哪里)评估顺序没有严格定义,所以你的代码不应该依赖或假设表达式中的函数将按特定顺序执行:在语句结束时所有引用的函数都将被调用,但编译器可以自由选择最有效的顺序。

标准是否指明了这个表达式的求值顺序?

if( functionA() && functionB() && functionC() ) cout<<"Hello world";

最佳答案

是的,C 和 C++ 标准中的运算符 ||&& 都需要短路和求值顺序。

C++ 标准说(C 标准中应该有一个等效的子句):

1.9.18

In the evaluation of the following expressions

a && b
a || b
a ? b : c
a , b

using the built-in meaning of the operators in these expressions, there is a sequence point after the evaluation of the first expression (12).

在 C++ 中有一个额外的陷阱:短路适用于重载运算符 ||&& 的类型。

Footnote 12: The operators indicated in this paragraph are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation, and the operands form an argument list, without an implied sequence point between them.

通常不建议在 C++ 中重载这些运算符,除非您有非常具体的要求。您可以这样做,但它可能会破坏其他人代码中的预期行为,尤其是如果这些运算符是通过实例化具有重载这些运算符的类型的模板间接使用的。

关于c++ - 是否强制要求短路逻辑运算符?和评价顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44554932/

相关文章:

c++ - 此代码是否检查字节顺序?

c++ - C++的2D分段/四元树解释

iphone - 使用 Core Audio 从 PCM 原始数据获取电平值

Python:为什么我的 'if' 语句的数字计算不正确?

c++ - 在 Visual Studio 2010 C/C++ 中, "Rescan Solution"操作的作用是什么?

c++ - 对于 `shared_ptr` 树结构,比 "widget"更好的选择?

c++ - Bitmask应该被提升到更多的可能性

c - 从类型 int 分配给类型 char[] 时类型不兼容

linux - bash 命令 XOR ^ 另一个命令

r - 当列包含因子时,使用OR子集数据框