是否强制要求短路逻辑运算符?和评价顺序? [英] Is short-circuiting logical operators mandated? And evaluation order?

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

问题描述

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

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.

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

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