Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all programming languages have boolean short-circuit evaluation?

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'; } ?> 
like image 858
Kim Stacks Avatar asked Aug 05 '09 11:08

Kim Stacks


People also ask

Does C++ have short-circuit evaluation?

c++ uses short-circuit evaluation in && and || to not do unnecessary executions. If the left hand side of || returns true the right hand side does not need to be evaluated anymore.

Does Python use short-circuit evaluation?

The Python or operator is short-circuiting When evaluating an expression that involves the or operator, Python can sometimes determine the result without evaluating all the operands. This is called short-circuit evaluation or lazy evaluation. If x is truthy, then the or operator returns x . Otherwise, it returns y .

Does Java have short-circuit evaluation?

Java's && and || operators use short circuit evaluation. Java's & and | operators also test for the "and" and "or" conditions, but these & and | operators don't do short circuit evaluation.

Does Python short circuit boolean expressions?

In python, short-circuiting is supported by various boolean operators and functions. The chart given below gives an insight into the short-circuiting case of boolean expressions. Boolean operators are ordered by ascending priority.


2 Answers

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.

like image 57
Patrick McDonald Avatar answered Sep 28 '22 20:09

Patrick McDonald


It's not true for VB6.

In VB.net you have to use "AndAlso" instead of "And" if you want it to skip evaluating the second expression.

like image 21
Alex Warren Avatar answered Sep 28 '22 20:09

Alex Warren