所有编程语言都有布尔短路评估吗? [英] Do all programming languages have boolean short-circuit evaluation?

查看:189
本文介绍了所有编程语言都有布尔短路评估吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP代码中

  if(a()&& b())
false
b()将不会被评估。



同样,在

  if(a()|| b())

当第一个操作数计算结果 true b()将不会被评估..



这适用于所有语言,如Java,C#等吗?



这是我们使用的测试代码。

 <?php 
function a(){
echo'a';
返回false;
}

函数b(){
echo'b';
返回true;
}


if(a()&& b()){
echo'c';
}
?>


解决方案

这叫做短路评估



对于派生的语言通常是正确的来自C(C,C ++,Java,C#)但不适用于所有语言。



例如,VB6不会这样做,也不会在早期版本中完成VB.NET。 VB8(在Visual Studio 2005中)介绍了 AndAlso 并为此目的 OrElse 运营商。



此外,根据评论,似乎csh从右到左执行短路评估,使问题更加令人困惑。



还应该指出,短路评估(或缺乏)有危险需要注意。例如,如果第二个操作数是一个具有任何副作用的函数,那么代码可能无法完全按照程序员的意图执行。


In the PHP code

if(a() && b())

when the first operand evaluates to false, b() will not be evaluated.

Similarly, in

if (a() || b())

when the first operand evaluates to true, b() will not be evaluated..

Is this true for all languages, like Java, C#, etc?

This is the test code we used.

<?php
function a(){
echo 'a';
return false;
}

function b(){
echo 'b';
return true;
}


if(a() && b()){
echo 'c';
}
?>

解决方案

This is called short-circuit evaluation.

It is generally true for languages derived from C (C, C++, Java, C#) but not true for all languages.

For example, VB6 does not do this, nor was it done in early versions of VB.NET. VB8 (in Visual studio 2005) introduced the AndAlso and OrElse operators for this purpose.

Also, from comments, it seems that csh performs short-circuit evaluation from right to left, to make matters even more confusing.

It should also be pointed out that short-circuit evaluation (or lack of) has its dangers to be aware of. For example, if the second operand is a function that has any side effects, then the code may not perform exactly as the programmer intended.

这篇关于所有编程语言都有布尔短路评估吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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