Short Circuit Evaluation in Programming

Short Circuit Evaluation is a technique where minimal evaluation is done while evaluating Boolean operators. An expression usually consists of more than one argument, and often we can determine the overall value for the expression, based of the first argument.

For example, in an AND expression between two arguments, if the first argument is False, then regardless of the value of the second argument, the overall expression value is False. Likewise, if the expression has the OR operator between two arguments, then if the first is True, the overall expression value is True.

In both cases, evaluating the second argument was not nessacery, and is a step that can be skipped. This concept is known as Short Circuit Evaluation.

A list of languages that support Short Circuit Evaluation:

Ada, Eiffel, ALGOL 68, C1, C++, C#, Java, R, Erlang, Standard ML, JavaScript, MATLAB, Lisp, Lua, Scheme, OCaml, Haskell, Pascal, Perl, Ruby, PHP, Python, Smalltalk, Visual Basic .NET


Uses of Short Circuit Evaluation

First and foremost, Short-Circuit-Evaluation is a performance optimization technique. Being able to skip the evaluation for some arguments helps speed up execution. However, this is a dependent on the Compiler and Computer Architecture, and one of those changes you wouldn’t make unless you actually had a performance bottleneck.

A second use case of Short Circuit, is to prevent the second argument from activating unless the first argument fails. You could make some rather interesting expressions using this logic, though coming up with the logic might be a little tricky.


Short-Circuit-Evaluation Examples

Before we begin with the examples, it’s worthwhile to mention that only some operators actually support Short Circuit Evaluation, out of which the most common two are the AND and OR operations. It’s not actually possible to apply Short-Circuiting on expressions with a single argument or operators like XOR, where both values are needed to determine the overall value.

(You will actually be hard-pressed to find any operator other than AND and OR that support Short Circuit Evaluation. Python for example, has no other operator besides AND and OR that does, as do most languages)

For example, when dividing a number we often place a check to prevent a division by zero. Let’s take a look at our first Short Circuit Evaluation expression where we implement this in a single line.

Below is some Python code we used to demonstrate this.

num = 8
div = int(input())

if (div != 0) and (num / div):
    print("...")

You might think that entering “0” as input would cause an error to be thrown on the num / div argument. However that is not the case, as the Short Circuiting will cause the execution to stop on the first argument, which checks whether div is 0 or not.

If you want to see how this would fail normally, change “and” to any other operator and watch how it fails.

Using Function Calls

Onto another example, this time in C++!

This time we are dealing with multiple function calls as the arguments . Whether or whether not a function call triggers will depend on the return value of the function call before it.

#include <iostream>
using namespace std;


bool isEven(int num) {
    if (num % 2 == 0) {
        cout << num << " is Even\n";
        return true;
    }
    else {
        return false;
    }
}


int main() {
    int num1 = 4;
    int num2 = 8;

    if ( isEven(num1) || isEven(num2) ) {   //  || is the OR operator
        //......
    }
}

In the above example, you might expect both functions call to trigger, but that is not the case! If you run the above code, only one statement will be printed on the console, despite both numbers being even.

This is because Short Circuit Evaluation, which determined the overall equation would be true, based of the first function call returning true. If you remember, the OR operator returns true, if any one of the two arguments is True. Hence if the first argument is True, we don’t need to bother checking the second one.


Pro Tip: Some languages like Java have Short-Circuit and Non-Short-Circuit versions of their operators. For example, they have && and &, and || and |.


Creating Complex Expressions

Finally let’s take a more practical situation as an example.

The below example uses a Plane as an example, which needs to do some checks before take-off.

bool checkEngine() {
    // if OK
    return true;
    // else
    return false;
}

bool checkFuel() {
    // if Full
    return true;
    // else
    return false
}

bool launchPlane() {
    // Some Code.......
    cout << "Plane Launched\n";
    return true;
}


int main() {
    if ( (checkFuel() && checkEngine()) && launchPlane() ) {
        // Further Code.....
    }
}

In the above example, we have created an interesting expression which uses brackets to created nested expressions. We have thus ended up in the following situation:

When evaluating the expression, first call the checkFuel() function. If it returns true (meaning that required fuel is in the tanks) then we move to the next function call. If it fails though we stop right here and evaluate the sub-expression checkFuel() && checkEngine() as false. By extension, the overall expression fails too as they have && operator between them.

In short, if the first function calls return false, then no other function call is made. Now let’s consider what happens when the first function call returns true.

Now the second function evaluates, and if it returns false, the sub-expression becomes false, resulting in the overall expression failing. If it returns true, meaning the engine was O.K, then we move to the third function call.

Now, as both of the pre-requisite functions returned true, the LaunchPlane() functions runs, and our goal is complete.


Ending Note

So that was it for our explanation on Short Circuit Evaluation in Programming.

There are some possible negative effects of this feature, for example, if you actually want the second argument to run, but Short Circuit Evaluation skipped it. This is also why some languages offer

There are some other very niche (rare) situations where this possibly causes issues and actually lowers performance, but for the most part you don’t need to worry about this.

Overall it’s a nice feature, and an interesting concept to know. Hopefully you found this article interesting and informative!


This marks the end of our Short Circuit Evaluation in Programming Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments