Skip to content
Related Articles

Related Articles

Improve Article

Short-circuit evaluation in Programming

  • Last Updated : 22 Jun, 2021

Short-Circuit Evaluation: Short-circuiting is a programming concept by which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined. Below is an example of the same:

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

C++




if (a == b || c == d || e == f) {
    // do_something
}

Explanation: In the above expression, If the expression a == b is true, then c == d and e == f are never evaluated at all because the expression’s result has already been determined. Similarly, if the logical AND (&&) operator instead of logical OR (||) and the expression a == b is false, the compiler will skip evaluating other sub-expressions.

Example 1:



C++




// C program to illustrate the concept
// of short circuiting
#include <stdio.h>
  
// Driver Code
int main()
{
    int x = 1;
  
    if (x || ++x) {
        printf("%d", x);
    }
  
    return 0;
}
Output
1

Explanation: In the above C program, inside the if statement, the value of the first sub-expression i.e., x is 1(which means true in boolean), so the value of the second sub-expression does not affect the value of the expression and hence the compiler skips checking it. So the value of x is not incremented.

Example 2:

C




// C program to illustrate the concept
// of short circuiting
#include <stdio.h>
  
// Driver Code
int main()
{
    int a = 10;
    int b = -1;
  
    // Here b == -1 is not evaluated as
    // a != 10 is false
    if (a != 10 && b == -1) {
        printf("I won't be printed!\n");
    }
    else {
        printf("Hello, else block is printed");
    }
  
    return 0;
}
Output
Hello, else block is printed

Explanation: The above program prints the output of the else block because the first condition is false which is sufficient to determine the expression’s value, so the second condition is not evaluated.

Example 3: Below is the C program to calculate the square root to demonstrate the concept of short-circuit evaluation:

C




// C program to illustrate the concept
// of short circuiting
#include <math.h>
#include <stdio.h>
  
// Function to calculate  the square root
int calculate_sqrt(int i)
{
    printf("Sqrt of %d: %.2f\n",
           i, sqrt(i));
  
    return i;
}
  
// Driver Code
int main()
{
    int a = 15;
  
    // Here since a is 10, calculate_sqrt
    // function will be called
    if (a >= 10 && calculate_sqrt(a)) {
        printf("I will be printed!\n");
    }
  
    return 0;
}
Output
Sqrt of 15: 3.87
I will be printed!

Explanation: In the above program if the number is less than 10 then the square root is not performed. Due to this the error are getting avoided for the negative number as well.



Applications: The concept of short-circuiting can be helpful in many scenarios. Some of them are listed below:

  • Avoiding unexpected behavior: It can be used to avoid unexpected behavior due to the second argument. For Example: consider the below code snippet:

C




// C program to illustrate the concept
// of short circuiting
#include <stdio.h>
  
// Driver Code
int main()
{
    float nr = 5, dr = 0;
    dr&& printf("a/b = %.2f", nr / dr);
}
Output
 

Explanation: As the expression (nr/dr) gives runtime errors but due to adding the expression dr && with the operation, the error avoided as the value of dr is 0 which excludes the computation of (nr/dr).

  • Avoiding Expensive Computation: It can be helpful in avoiding expensive computations which are required to be executed only under specific conditions. Below is the code snippet to illustrate the same:

C




int a = 0;
  
// myfunc(b) will not be called
if (a != 0 && myfunc(b)) {
    // do_something();
}

Examples: In the above example, if it is required to do an expensive operation using the myfunc() for the value 0, then the expensive operation for the non-zero values can be avoided by using this concept. This can also be used in file handling to avoid the expensive task of getting a file ready every time if the file is already in a ready state as

isFileReady() || getFileReady()
 

Advantages Of Short-Circuit Evaluation:

  • It can be helpful in avoiding computationally expensive tasks under certain circumstances.
  • It provides a check for the first argument without which the second argument may result in a runtime error.

Disadvantages Of Short-Circuit Evaluation:

  • It can cause unexpected behavior if not used properly. For any function in the code snippet that does some kind of allocation of system resources/memory allocation, we may get unexpected behavior.
  • Code execution becomes less efficient with short-circuited execution paths because in some compilers the new checks for short-circuits are extra execution cycles in themselves.



My Personal Notes arrow_drop_up
Recommended Articles
Page :