gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:13:19 28 4
gpt4 key购买 nike

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/58065364/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com