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.