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/