Short Circuit Evaluation

Short-circuiting is where an expression is stopped being evaluated as soon as its outcome is determined.
For example consider the expression "If ( (a = b) or (c = d) ) Then DoSomething"
If "a = b" then we do not need to check if "c = d" because we know the outcome will be True.


Excel Functions

The IF Function does use short circuiting.
Only LongFormula1 gets evaluated
Only LongFormula2 gets evaluated

 A
1'=IF(TRUE, LongFormula1, LongFormula2)
2'=IF(FALSE, LongFormula1, LongFormula2)

In this example A1 will get evaluated twice.
Although in Excel 2007 this could be replaced with the following, so B1 only gets evaluated once.

 AB
1=IF(ISERROR(B1),FALSE,B1) 
2=IFERROR(B1,FALSE) 

The AND function does not use short circuiting, both expressions get evaluated
The OR function does not use short circuiting, both expressions get evaluated

 A
1=AND(FALSE, #N/A) = #N/A
2=OR(TRUE, #N/A) = #N/A

VBA Language

VBA does not support any short-circuit operators
And and Or will always evaluate all the expressions. In this example VeryLongFunction is called even though the result will be False.

Public Sub NoShortCircuit() 
   If (False And VeryLongFunction) Then
      Call MsgBox("hello")
   End If
End Sub
Public Function VeryLongFunction() As Boolean
End Function

You can implement the equivalent by using nested IF statements.

Public Sub NoShortCircuit() 
   If (False) Then
      If (VeryLongFunction) Then
         Call MsgBox("hello")
      End If
   End If
End Sub

JavaScript Language

In JavaScript the following operators are short-circuit operators
When Logical OR sees a falsy value, it continues evaluating. Once it gets to a value it stops.

&& (and) 
|| (or)
! (not)

C# Language

In C# the following operators are short-circuit operators

&& (and) 
|| (or)
? (conditional operator or ternary operator)
?? (null-coalescing operator)

VB.Net Language

In VB.Net the following operators are short-circuit operators

AndAlso 
OrElse

© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrevNext