Open In App

Short-circuit evaluation in Programming

Last Updated : 16 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Short-Circuit Evaluation: Short-circuiting is a programming concept in 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:

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 not evaluated because the expression’s result has already been determined. Similarly, if the logical AND (&&) operator is used 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 x = 1;
    int y = -1;
 
    // Since x == 50 evaluates to false, the second sub-expression is
    // also evaluated, value of y is incremented to 0 (false in boolean).
    // As a result else block is executed and the incremented value of y is
    // printed from within the else block
    if (x == 50 || ++y) {
        printf("if block executed\n");
        printf("Value of y: %d", y);
    }
    else {
        printf("else block executed\n");
        printf("Value of y: %d", y);
    }
    return 0;
}


Output

else block executed
Value of y: 0

Explanation: Since x == 50 evaluates to false, the second sub-expression is also evaluated, and the value of y is incremented to 0 (false in boolean). As a result else block is executed and the incremented value of y is printed from within the else block.

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

// No output

Explanation: Here since the value of dr is 0 (false in boolean), the expression nr/dr inside printf will not be evaluated and runtime error will be avoided.

  • 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();
}


Explanation: In the above example, myfunc() will never be called since a != 0 evaluates to false. Thus, if an expensive operation is to be carried out using myfunc() only under certain conditions, then the expensive operation can be avoided from being carried out every time by using a suitable condition for the first argument.

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. If some operation that does some kind of allocation of system resources/memory allocation gets skipped due to short-circuiting, 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.


Similar Reads

What is evaluation order of function parameters in C?
It is compiler dependent in C. It is never safe to depend on the order of evaluation of side effects. For example, a function call like below may very well behave differently from one compiler to another: void func (int, int); int i = 2; func (i++, i++); There is no guarantee (in either the C or the C++ standard language definitions) that the incre
1 min read
Evaluation order of operands
Consider the below program. C/C++ Code // C++ implementation #include &lt;bits/stdc++.h&gt; using namespace std; int x = 0; int f1() { x = 5; return x; } int f2() { x = 10; return x; } int main() { int p = f1() + f2(); cout &lt;&lt; (&quot;%d &quot;, x); getchar(); return 0; } C/C++ Code #include &lt;stdio.h&gt; int x = 0; int f1() { x = 5; return
3 min read
Learn Programming Languages- List of 11 Popular Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. It is an essential part of software development because it creates a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, search the internet, you w
9 min read
Sort an array using socket programming in C
Given an array of unsorted positive integer, sort the given array using the Socket programming . Examples: Input : 4 5 6 1 8 2 7 9 3 0 Output :0 1 2 3 4 5 6 7 8 9 Input : 9 8 1 4 0 Output : 0 1 4 8 9 Compile these files using gcc command (gcc client.c -o client and gcc server.c -o server). Run the program using ./server and ./client (Please note :
3 min read
AKTU (UPTU) Previous Year Solved Papers | C Programming
This article contains the previous year papers of AKTU for the subject of Fundamentals of C Programming. 2017-18 Semester 1: AKTU 1st Year Sem 1 Solved Paper 2017-18 | COMP. SYSTEM & C PROGRAMMING | Sec A AKTU 1st Year Sem 1 Solved Paper 2017-18 | COMP. SYSTEM & C PROGRAMMING | Sec B AKTU 1st Year Sem 1 Solved Paper 2017-18 | COMP. SYSTEM & C PROGR
3 min read
Working of Keyword long in C programming
In C, long is a keyword that symbolizes the Long datatype. The long data type is a 64-bit two's complement integer with: Size: 64 bit Value: -263 to 263-1 The output of 64 bit GCC compiler would give the size of long as 8 whereas on 32 bit GCC compiler the size would be 4. So it varies from compiler to compiler. Now the question is what exactly is
3 min read
Draw a moving car using computer graphics programming in C
In computer graphics, use graphics.h which provide direct functions to draw different coordinate shapes (like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees, etc. In this program, we will draw a moving car using line and circles. Functions used in program: delay(n): This function is used for hold
4 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to create GUI in C programming using GTK Toolkit
Introduction to GTK Many programming languages bolster GUI improvement as one of the centrepieces of its language highlights. C has no such library connected to it like the string library, IO library, etc, that we every now and again use. This weakness opened the skyline for engineers to pick from a wide assortment of GUI library toolbox accessible
7 min read
Introduction to the C99 Programming Language : Part I
Introduction: C99 is a standardized version of the C programming language that was published in 1999 by the International Organization for Standardization (ISO). It introduced a number of new features and improvements over the previous C89 standard, including support for variable-length arrays, flexible array members, complex numbers, and new keywo
8 min read
Introduction to the C99 Programming Language : Part II
In this article, we are going to discover some more interesting additions to C89 which gave us C99 standard: Variable Argument Lists: C99 brings out a small changes to the preprocessor. Macros can accept a variable number of arguments. These Macros are indicated by ellipsis (...) in their declaration. These Variable Arguments are represented by the
4 min read
Introduction to the C99 Programming Language : Part III
Kindly read Introduction to the C99 Programming Language (Part I) and Introduction to the C99 Programming Language (Part II) before reading this article. Addition of Library Functions: C99 provides some Additional Library functions listed below. Library Function Usage complex.h complex.h supports complex arithmetic fenv.h fenv.h gives access to flo
3 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys
3 min read
Getting System and Process Information Using C Programming and Shell in Linux
Whenever you start a new process in Linux it creates a file in /proc/ folder with the same name as that of the process id of the process. In that folder, there is a file named "status" which has all the details of the process. We can get those Process Information Through shell as follows: cat /proc/1/status As can be seen, it displays most of the i
2 min read
Top 10 Programming Languages for Blockchain Development
Do you ever wonder about the sudden emergence and popularity of Blockchain? What is it? Well, Blockchain is literally a chain of blocks as the name suggests! It’s just that the “blocks” in this context are digital information that is connected using cryptography. Each of these blocks contains a cryptographic hash function linking to the previous bl
7 min read
Draw a Chess Board using Graphics Programming in C
Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? In Computer Graphics, we use graphics.h which provide direct functions to draw different coordinate shapes(like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees etc. In this program, the task is to draw a Chess Board using the funct
4 min read
What are the C programming concepts used as Data Structures
Data Types Data-type in simple terms gives us information about the type of data. Example, integer, character, etc. Data-types in C language are declarations for the variables. Data-types are classified as: Primitive or Built-in data types Some of the examples of primitive data types are as follows Variable named ch refers to the memory address 100
10 min read
Brief Overview &amp; Comparison of Object-Oriented Programming from C to Java
In this article, you will get the ability to think how really OOP works in Java through C. Through C, you will understand the concept of Polymorphism, Inheritance, Encapsulation, Class, Objects, etc. As you also know C language don't support OOP, but we can understand the concept behind it by defining a fine structure as a Class and Creating its Id
3 min read
Different Ways to Setting Up Environment For C++ Programming in Mac
Xcode is an IDE developed by Apple themselves to develop apps for macOS and iOS or all other Operating Systems that Apple develops. It also has support for C/C++ built-in. Here, finding a C++ IDE for a macOS system is quite easy. To run a program in C++ in Mac we have to install Xcode or command-line tools for Xcode. Ways: Hence, there are two opti
3 min read
Handling multiple clients on server with multithreading using Socket Programming in C/C++
This tutorial assumes that the reader has a basic knowledge of socket programming, i.e has a familiarity with basic server and client models. In the basic model, the server handles only one client at a time, which is a big assumption if one wants to develop any scalable server model. The simple way to handle multiple clients would be to spawn a new
6 min read
Structured Programming Approach with Advantages and Disadvantages
Structured Programming Approach , as the word suggests, can be defined as a programming approach in which the program is made as a single structure. It means that the code will execute the instruction by instruction one after the other. It doesn't support the possibility of jumping from one instruction to some other with the help of any statement l
2 min read
Interesting Facts in C Programming | Set 2
Below are some more interesting facts about C programming: 1. Macros can have unbalanced braces: When we use #define for a constant, the preprocessor produces a C program where the defined constant is searched and matching tokens are replaced with the given expression. Example: C/C++ Code #include &amp;lt;stdio.h&amp;gt; // Declaring Macro // with
2 min read
C Exercises - Practice Questions with Solutions for C Programming
The best way to learn C programming language is by hands-on practice. This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more. So, Keep it Up! Solve topic-wise C exercise questions to streng
12 min read
Buffer in C Programming
In C, the buffer is referred to as a sequential section of memory that is used to temporarily store some data that is being transferred from one place to another. For Example, in C language, the data entered using the keyboard is first stored in the input buffer, and then it is stored in the memory. In this article, we will discuss what is a buffer
5 min read
C Programming Language Standard
Introduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the features that are still used in modern C programming, in
6 min read
A C Programming Language Puzzle
Give a = 12 and b = 36 write a C function/macro that returns 3612 without using arithmetic, strings and predefined functions. We strongly recommend you to minimize your browser and try this yourself first. Below is one solution that uses String Token-Pasting Operator (##) of C macros. For example, the expression "a##b" prints concatenation of 'a' a
1 min read
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:
2 min read
Creating a Rainbow using Graphics Programming in C
In Turbo C graphics we use graphics.h functions to draw different shapes(like circle, rectangle etc), display text(any message) in different format(different fonts and colors). By using graphics.h we can make programs, animations and also games. These can be useful for beginners. Functions Used : delay(n): A function from dos.h header file is respo
2 min read
Benefits of C language over other programming languages
C is a middle-level programming language developed by Dennis Ritchie during the early 1970s while working at AT&amp;T Bell Labs in the USA. The objective of its development was in the context of the re-design of the UNIX operating system to enable it to be used on multiple computers. Earlier the language B was now used for improving the UNIX system
3 min read
How to Setup VSCode with C, C++ and Python for Competitive Programming
VSCode is a Text editor that provides support for development operations and version control systems. It provides tools for a user to build hassle-free codes. VSCode can be downloaded and installed from visualstudio.com This article will show you how to, fetch test cases directly from the browser without copy-pasting and run them in VSCode with jus
5 min read
Article Tags :