Logical Operators
These operators are used to evaluate expressions which may be true or false. For a condition to be true or for non-zero value,result evaluates to 1(one) otherwise 0(zero).
C has the following logical operators, they compare or evaluate logical and relational expressions.
|
Operator |
Meaning |
|
&& |
Logical AND |
|
|| |
Logical OR |
|
! |
Logical NOT |
priority order : &&, || , ! and expression will be evaluated from left to right.
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.
truth table
| left exp. | right exp. | result |
| 0 | 0 | 0 |
| 0 | non-zero | 0 |
| non-zero | 0 | 0 |
| non-zero | non-zero | 1 |
Example
c = (a > b && x = = 10)
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
let us suppose a=10,b=7 and x =10 then result will be c = 1 as both expressions are true . But if we take x=8 then result will be c=0 as expression on the right side of AND operator is false.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.
truth table
| left exp. | right exp. | result |
| 0 | 0 | 0 |
| 0 | non-zero | 1 |
| non-zero | 0 | 1 |
| non-zero | non-zero | 1 |
Example
a < m || a < n
The expression evaluates to true if any one of them is true . It evaluates to true if a is less than either m or n.
note: In case of OR operator ,if left expression of “||” is true then right expression will not be checked or evaluated.
Example:
int a= 100,b=200,c;
c=(a==100||b>200);
printf(”c = %d “,c);
output:
c=1
since in expression c=(a==100||b>200) left of || is true,therefore without concerning right side of OR operator.
let us take another example.
int i = -3,j=2,k=0,m;
m = ++i || ++j && ++k;
now result is
i= -2 , j=2, k=0, m=1.
Explanation : According to priority order AND will evaluate first. Now on LHS of AND operator,we have OR operator,so left of OR will be evaluate,therefore,i = -2 (i++) and this implies left expression is true,therefore,right expression(++j && ++k) will not be evaluate so j= 2 and k=0. Hence m=1.
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression.
truth table
| exp. | result |
| 0 | 1 |
| non-zero | 0 |
For example
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y



Recent Comments