Logical Operators in C
For Complete YouTube Video: Click Here
In this class, we will try to understand Logical Operators in C.
We had a clear understanding of Arithmetic, Assignment, Increment-decrement, Bitwise, Shift, Ternary, And Relational Operators in our previous classes.
Table of Contents
Logical Operators in C
The image below shows the logical operators.
There are three different types of Logical Operators in C.
- Logical AND [&&]
- Logical OR [||]
- Logical NOT [!]
Logical AND and Logical OR are binary operators.
Logical NOT is a unary operator.
All the logical operators produce an output of either 1 or 0.
Logical AND [&&]
How logical AND operator will get executed?
The Logical AND operator produces an output of 1 if both the operands produce an output of 1.
It produces an output of 0 if any of the operands produce a 0 or if both the operands produce 0.
The example below helps us to have a clear understanding.
a = 4 b = 3
(a != 0) && ( a+b > 5 )
Both the operands of the above expression will produce 1.
As both the operands are one, the logical AND will produce one as its output.
Logical OR [||]
How logical OR operator will get executed?
The Logical OR operator produces an output of 1 if any one of the operands produces a one or if both operands produce 1.
It produces an output of 0 if both the operands produce a 0.
The example below helps us to have a clear understanding.
a = 4 b = 3
(a == 0) || ( a+b > 5 )
In the above expression, a==0 produces 0 and a+b>5 produces a 1.
As one of the operands is one, the logical OR will produce one as its output.
Logical NOT [!]
Logical NOT is a unary operator.
Logical NOT negate or compliments the output of the evaluation of the expression.
The example below helps us to have a clear understanding.
a = 4 b = 3
! ( a == 4)
! (a == 0) && ( a+b > 5 )
The output of the a==4 is 1, but the NOT operator negates it to 0.
Similarly, in the second expression, a==0 produces 0, but the NOT operator negates it to 1.
The overall expression produces an output of 1.
In our discussion on Relational and equality operators we discussed an example a<b<c where the values of a=2, b=3, and c=4.
The expression a<b<c seems to be good but the c compiler will evaluate in a different way.
The above expression can written by using logical operators as shown below.
a< b && b<c.
Now the expression is logically correct.