是否强制使用短路逻辑运算符?和评价顺序?

Is short-circuiting logical operators mandated? And evaluation order?(是否强制使用短路逻辑运算符?和评价顺序?)

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

问题描述

ANSI 标准是否要求在 C 或 C++ 中逻辑运算符要短路?

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).

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

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

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

通常不建议在 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.

这篇关于是否强制使用短路逻辑运算符?和评价顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:是否强制使用短路逻辑运算符?和评价顺序?

基础教程推荐