Shortcut evaluation of an expression is a computer optimization. For example if you know three things must all be true in order to proceed, you do not need to check condtions 2 and 3 if condition one is already known to be false. (See Logic)

In most languages we use the && notation for AND and the || notation for OR. The interesting thing about the these operations is that they behave in what is known as "Short Cut" evaluation.

Assume we have three boolean expressions A,B, and C. If we put them in an conditional statement using && we get:

if ( A && B && C ) { do something; }

We know that the only way this expression can be true is if A and B and C are all true. BUT, if A is false, we don't even need to consider B and C because we already know the entire expression is false.

Short Cut evaluation means that as soon as the program can
determine that the expression is false **No Further Evaluation**
takes place.

Similar to AND, OR can also terminate early. For example:

if (A || B || C) { do something; }

What can the computer do if A is known to be true. Does the value of B or even C matter at that point?

Why is shortcut evaluation nice? The answer is Time and in some cases, safety. In general, not having to do work in a program makes the program run faster. This is almost always a good thing.

Sometimes it is very important **not** to do the second part of
an expression. For example, if we are accesing the memory in an
array and the location (or index) in the array is too big, then the
program could crash. To safe guard, we often use this canonical notation::

if ( length(array) >= 5 && array(5) == 100) { do something; }

Notice: First we check to make sure that the array is
long enough to hold 5 values, and then we access the 5th
bucket. If the array only had one item in it, then the
second half of the boolean expression would result in
an "Index exceeds matrix dimensions" error, **STOPPING**
our program!

Back to Topics List