Short Circuit Evaluation in Logical Operators.

Short-Circuiting in Logical Operators is an important concept to understand in programming in which the compiler skips the evaluation of sub-expressions in a Logical expression. The compiler does this because evaluating the remaining expression will cause no change in the overall result. 


Boolean AND (&&) and OR (||) logical operators perform short-circuit evaluation.

Short-circuit in case of AND (&&) operator: AND operator is used to combine two conditions together and the second condition is evaluated only when the first condition returns true. (alert-success)

Example

//C++ Example of Short Circuit AND Operators
#include<iostream>
using namespace std;

int main(){

    int a = 6, b = 2;

    bool check = (a < b) && (++b);
    cout<<"Expression is "<<check<<endl;
    cout<<"b = "<<b<<endl;

    return 0;
}
Output:
Expression is 0
b = 2

In the above example code, we have combined two conditions using AND (&&) operator, and when the first condition of the expression returned false compiler didn't move to the second increment condition so the value of b remains the same. This is how short-circuiting took place in the logical AND operator.

Short-circuit in case of OR (||) operator: OR operator is used to combine two conditions together and the second condition is evaluated only when the first condition returns false. (alert-success)

Example: 

//C++ Example of Short Circuit OR Operators
#include<iostream>
using namespace std;

int main(){

    int a = 8, b = 2;

    bool check = (a > b) || (++b);
    cout<<"Expression is "<<check<<endl;
    cout<<"b = "<<b<<endl;

    return 0;
}

Output:

Expression is 1
b = 2

In this example, we have used the boolean OR (||) operator to combine the conditions and you can observe that compiler didn't move to the second increment condition as soon as it found that the first condition is already true. This is how the entire expression is not evaluated to get the overall output.
Short circuit evaluation might cause unexpected behavior if you don't use this concept properly. As the second expression is not evaluated after the first expression so there is a chance of runtime error as the complete expression is not evaluated each time. (alert-warning)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS