c++,使用多个“&&”评估表达式,并且没有较低优先级的运算符
如果表达式计算多个 &&
运算符,并且不计算任何较低优先级的运算符(例如 ||
、?:
) ,一旦其中一个 &&
返回 0,表达式的计算结果是否会为 0,还是会完成剩余 &&
的计算?
例如,
q=0; w=1; e=1; r=1;
if(q && w && r && e) {}
一旦 q && ,此
的计算结果为 0(因为无论右手运算符如何,其余的 if()
的计算结果是否为 false? w&&
都必须计算为 0)?
If an expression evaluates multiple &&
operators, and does not evaluate any operators of lower precedence (eg. ||
, ?:
), will the expression evaluate to 0 as soon as one of the &&
s return 0, or will it finish evaluating the remaining &&
s?
For example,
q=0; w=1; e=1; r=1;
if(q && w && r && e) {}
Will this if()
evaluate to false as soon as q && w
evaluates to 0 (since the remaining &&
must all evaluate to 0 regardless of the right hand operators)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,一旦遇到错误表达式,计算就会提前终止(“短路”)。有一个例外:如果
&&
运算符已针对相关类型的参数重载。强烈建议不要这样做,而且这种情况极其罕见,但也有可能发生。Yes, evaluation will terminate early ("short circuit") as soon as a false expression is encountered. There is one exception to this: if the
&&
operator has been overloaded for the relevant types of arguments. This is strongly discouraged and extremely rare, but could happen.是的,它确实对内置类型进行短路评估。重载
&&
或||
的自定义类型不会执行短路,这可能会导致细微的错误。Yes, it does do short-circuit evaluation, for built-in types. Custom types where you've overloaded
&&
or||
won't have short-circuiting performed, which can cause subtle bugs.其他人已经说出了答案(即“是”)。
我将回答添加一个特别惯用的用法的示例:
如果没有发生短路,则必须以一种更加笨拙的方式编写。
请注意,您还可以以 Perl 式的方式使用它,例如:
只有当
someCondition
为true
时,才会调用doSomething()
。但只有当doSomething()
返回一个可以转换为bool
的类型时,它才会编译,并且它不被认为是惯用的C++。 (另请注意,该技术不能在 C 中编译。)Others have already stated the answer (i.e. "yes").
I will answer to add an example of one particularly idiomatic usage of this:
This would have to be written in a much clumsier manner if short-circuiting didn't happen.
Note that you can also use this in a Perl-esque manner, e.g.:
so
doSomething()
only gets called ifsomeCondition
istrue
. But this only compiles ifdoSomething()
returns a type that can be converted tobool
, and it's not considered idiomatic C++. (Note also that this technique doesn't compile in C.)