Short-circuit+evaluation

//by Richard Russell, December 2009//

Consider a compound conditional test such as the following:

code format="bb4w" IF condition1 AND condition2 AND condition3 THEN code It can be seen that if **condition1** is FALSE then the entire expression must be FALSE, irrespective of the results of the other conditions. Ideally, in such a case it would be better not to waste time evaluating **condition2** and **condition3** because they cannot affect the overall outcome. Similarly if **condition2** is false, ideally you shouldn't evaluate **condition3**.

Skipping the subsequent conditions in this way, when they cannot affect the result, is called [|Short-Circuit Evaluation] and some languages (e.g. C) provide special operators to support it. However, BASIC generally doesn't.

Because the performance benefits from Short-Circuit Evaluation may be substantial (especially if the expressions involve one or more function calls) it would be highly desirable to emulate this behaviour, and fortunately in BBC BASIC there is an easy way to do so:

code format="bb4w" IF condition1 IF condition2 IF condition3 THEN code Here the **AND**s have simply been changed to **IF**s. If **condition1** is FALSE neither **condition2** nor **condition3** is evaluated. If **condition1** is TRUE but **condition2** is FALSE, **condition3** is not evaluated.

A similar situation arises when the conditions are combined using **OR**:

code format="bb4w" IF condition1 OR condition2 OR condition3 THEN code Here, if **condition1** is TRUE (strictly, not FALSE) the entire expression must be TRUE, irrespective of the results of the other conditions, and it would be better not to waste time evaluating **condition2** and **condition3**.

Unfortunately there isn't such a straightforward way of emulating this in BASIC as in the **AND** case. However it is possible to achieve the desired effect as follows:

code format="bb4w" IF condition1=FALSE IF condition2=FALSE IF condition3=FALSE THEN ELSE REM Carry out the required actions here ENDIF code Effectively what we have done here is to use [|De-Morgan's theorem] to convert the **OR** expression into an **AND** expression, and to reverse the result by putting the required actions into the ELSE clause.

To gain the maximum benefit from Short-Circuit Evaluation you should make the **first** condition in the set the one **least likely** to be met, and you should make the slowest-to-evaluate condition the **last** in the set.

You must take into account any //side effects// from evaluating the conditions. If one or more of the conditional expressions calls a user-defined function, and if that function has a side-effect which can affect the operation of the program, then changing from conventional evaluation to Short-Circuit evaluation will cause that side-effect to occur conditionally upon the result(s) of earlier conditions rather than than always occurring.