Logical Operators
There are three logical operators in C language:
! | Logical NOT |
&& | Logical AND |
|| | Logical OR |
Logical NOT
Logical NOT operator is also a unary operator, as it requires only one operand. Operand is treated as either true or false. NOT operator inverts the truth value, that is, it make false if the operand is true and makes true if the operand is false.
Example
main()
{
int x;
x=!(5>4);
printf("x=%d",x);
}
Output is
x=0
Explanation
In the expression x=!(5>4), bracket operates first, so the result of 5>4 is 1 (true). This result becomes the operand of logical NOT operator, which makes it 0 (false). Thus the value stored in x is 0.
Example
main()
{
int x;
x=!4;
printf(“x=%d”,x);
}
Output is
x=0
Explanation
In the expression x=!4, 4 is the operand of logical NOT operator. 4 is treated as true. Remember every non-zero value is true and zero is false. 4 is a non zero value, so it is treated as true. Now logical NOT operator inverts the truth value from true to false and therefore 0 is stored in x.
Logical AND
Logical AND operator is used to combine two expression, thus it is a binary operator.
The behavior of logical AND is describes as:
Expression 1 | && | Expression 2 | Result |
True | && | True | True |
True | && | False | False |
False | && | Don’t Care | False |
Example
int main()
{
int x;
x= 5>3&&4<0;
printf(“%d”,x);
return(0);
}
Output is:
0
Explanation
Here, two conditions 5>3 and 4<0 are combined to form a single condition using && operator as 5>3&&4<0. Condition one is evaluated as TRUE as 5 is greater than 3. Since condition one is TRUE condition two is tested and evaluated as FALSE as 4 is not less than 0. According to the above chart, T&&F is treated as FALSE thus 0 is stored in x.
Logical OR
Logical OR operator is also used to combine two expressions. This is a binary operator. The behavior of logical OR operator is:
Expression 1 | || | Expression 2 | Result |
False | || | False | False |
False | || | True | True |
True | || | Don't Care | True |
Example
int main()
{
int x,y=5;
x= y>10||y<7;
printf(“%d”,x);
return(0);
}
Output is:
1
Explanation
In the expression x=y>10 ||y<7, y>10 is false, so we check expression 2 and y<7 is true, therefore operands of logical OR operator are false and true. The result is then evaluated as true, this result is assigned to variable x. Since true is represented as 1 (one) therefore x is assigned 1.