Do all programming languages have boolean short-circuit evaluation?

Kim Stacks picture Kim Stacks · Aug 5, 2009 · Viewed 11.1k times · Source

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';
}
?>

Answer

Patrick McDonald picture Patrick McDonald · Aug 5, 2009

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.