Short Circuit Method for Logical AND and Logical OR
For Complete YouTube Video: Click Here
Short Circuit Method for Logical AND and Logical OR
In this class, we will try to understand Short Circuit Method for Logical AND and Logical OR.
We have already discussed logical operators in our previous classes.
Table of Contents
Short Circuit Method
What is the Short Circuit Method?
The Short Circuit Method is the way expressions with logical AND or logical OR operators will get evaluated.
Consider the examples below to have a clear understanding of the Short Circuit Method.
Example 1:
a = 2 b= 3 c = 4
(a < b) && (c > b) && (a + c > 3) && (a == 0) && (c >= b)
&& (! (a + b > 3))
Example 2:
a = 2 b= 3 c = 4
(a > b) || (c < b) || (a + c < 3) || (a == 2) || (c >= b) || (! (a + b > 3))
Example 1 is using the Logical AND operators.
a = 2 b= 3 c = 4
(a < b) && (c > b) && (a + c > 3) && (a == 0) && (c >= b)
&& (! (a + b > 3))
The above expression will produce one if all the sub-expressions with Relational and Equality operators evaluate to true.
The image below shows the evaluation of the expression after substituting the values.
In C Programming, all the sub-expressions will NOT be evaluated.
To evaluate this kind of expression, C Programming uses Short Circuit Method.
How will the expression be evaluated using the short circuit method?
In the evaluation process, if any one of the sub-expression evaluates to 0 [false], the remaining sub-expression will NOT be assessed.
The image below shows the actual evaluation of the expression.
The sub-expression a==0 evaluates to false.
The sub-expressions after that will not be evaluated because how many expressions it may determine will result in false.
Similarly, example 2 is using the Logical OR operators.
a = 2 b= 3 c = 4
(a > b) || (c < b) || (a + c < 3) || (a == 2) || (c >= b) || (! (a + b > 3))
The above expression will produce one if any one of the sub-expressions with Relational and Equality operators evaluate to true.
The image below shows the evaluation of the expression after substituting the values.
How will the expression be evaluated using the short circuit method?
In the evaluation process, if any one of the sub-expression evaluates to 1 [true], the remaining sub-expression will NOT be assessed.
The image below shows the actual evaluation of the expression.
The sub-expression a==2 evaluates to true.
The sub-expressions after that will not be evaluated because how many expressions it may determine will result in true.
Problems with Short Circuit Method
Let us try to understand the problem with Short Circuit Method for Logical AND and Logical OR by using the example below.
a=2, b=3, c=4;
(a < b) && (++c < 7)
From the above program, a<b is false.
Using the short circuit method, the expression (++c<7) will not be executed.
As the expression is using ++c, the value of c will never be incremented.
The programmers should be careful with Short Circuit Method for Logical AND and Logical OR.