是否必须使逻辑运算符短路?和评估顺序? [英] Is short-circuiting logical operators mandated? And evaluation order?

查看:115
本文介绍了是否必须使逻辑运算符短路?和评估顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C或C ++中,ANSI标准授权是要短路的逻辑运算符吗?

Does the ANSI standard mandate the logical operators to be short-circuited, in either C or C++?

我很困惑,因为我回想起《 K& R》一书,说您的代码不应该依赖于这些短路的操作,因为它们可能并非如此.有人可以指出逻辑运算符在标准中总是短路的地方吗?我对C ++最为感兴趣,对于C的回答也很好.

I'm confused for I recall the K&R book saying your code shouldn't depend on these operations being short circuited, for they may not. Could someone please point out where in the standard it's said logic ops are always short-circuited? I'm mostly interested on C++, an answer also for C would be great.

我还记得阅读(不记得在哪里)评估顺序没有严格定义,因此您的代码不应依赖或假定表达式中的函数将按特定顺序执行:在语句末尾所有引用的函数都将被调用,但是编译器可以自由选择最有效的顺序.

I also remember reading (can't remember where) that evaluation order isn't strictly defined, so your code shouldn't depend or assume functions within an expression would be executed in a specific order: by the end of a statement all referenced functions will have been called, but the compiler has freedom in selecting the most efficient order.

标准是否表明该表达式的求值顺序?

Does the standard indicate the evaluation order of this expression?

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

推荐答案

是的,在C和C ++标准中,运算符||&&都需要短路和评估顺序.

Yes, short-circuiting and evaluation order are required for operators || and && in both C and C++ standards.

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

C++ standard says (there should be an equivalent clause in the C standard):

1.9.18

在评估以下表达式时

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

使用这些表达式中运算符的内在含义,在第一个表达式求值之后有一个序列点(12).

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 ++中有一个额外的陷阱:短路确实不会适用于重载运算符||&&的类型.

In C++ there is an extra trap: short-circuiting does NOT apply to types that overload operators || and &&.

脚注12:本节中指示的运算符是内置运算符,如第5节所述.当这些运算符之一在有效上下文中超载时(第13节),因此指定了用户定义的运算符函数,该表达式指定函数调用,并且操作数形成一个参数列表,它们之间没有隐含的序列点.

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 ++中重载这些运算符,除非您有非常具体的要求.您可以这样做,但是这样做可能会破坏其他人代码中的预期行为,尤其是如果通过实例化模板以使这些操作符类型超载的方式间接使用这些操作符时.

It is usually not recommended to overload these operators in C++ unless you have a very specific requirement. You can do it, but it may break expected behaviour in other people's code, especially if these operators are used indirectly via instantiating templates with the type overloading these operators.

这篇关于是否必须使逻辑运算符短路?和评估顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆