Table of Contents
show
Logical operators are used to logically relate the sub expression
- In C, there is no operator for Exclusive or (XOR)
- Logical operators work according to the truth table
- If an operand of a logical operator is a non-zero value, the operand is considered as true. If the operand is zero, it is false
- Each of the logical operator yields 1, if the specified condition evaluates to True
The logical operators are listed as,
The truth table are given as,
AND Operator
OR Operator
NOT Operator
Example
Illustration of Logical operator
#include<stdio.h>
int main()
{
int i = 0, j = 1, k = 2, res;
res = i && j++ && k++;
printf("i=%d,j=%d,k=%d,res=%d",i,j,k,res);
return 0;
}
Output
i=0,j=1,k=2,res=0
Explanation
- i is 0 therefore j++ is not executed.
- Similarly k ++ is not executed and 0 is assigned to res
Illustration of Logical operator
#include<stdio.h>
int main()
{
int i = 0, j = 1, k = 2, res;
res = i && j++ || k++;
printf("i=%d,j=%d,k=%d,res=%d",i,j,k,res);
return 0;
}
Output
i=0,j=1,k=3,res=1
Explanation
- i is 0 therefore j++ is not executed. Because of the use of ||
- k++ is evaluatedres = 0||2 is executed and then k = k+1 executes
Views: 0