Logical operators are used when we want to test more than one condition and make decisions. Logical expressions also give 1 (if true), and 0 (if false).
Operator | Meaning | Description |
---|---|---|
&& | logical AND | Compares two test conditions. For example, to test if the number x lies between 10 and 20, the expression will be x > 10 && x <20. Both conditions must be true to satisfy the condition. It results 1 (if true) and 0 (if false). |
|| | logical OR | This condition is satisfied if one of the test conditions is true. For Example to check whether the number x is negative or even the expression will be (x < 0) || (x % 2 == 0) |
! | logical NOT | This expression is used to reverse the logic. For example, if x is equal to 1 (true), then applying this operator results in 0 (false). |
The expression on the left and right-hand sides of the logical operator will be either non-zero(true) or zero (false). We can see all the cases of results of this operator in the form of the truth table.
Operand1 | Operand2 | Operand1 && Operand2 | Operand1 || Operand2 | !Operand1 |
---|---|---|---|---|
0 | 0 | 0 | 0 | 1 |
0 | Non-zero | 0 | 1 | 1 |
Non-zero | 0 | 0 | 1 | 0 |
Non-zero | Non-zero | 1 | 1 | 0 |
Whatever the expression is the result will be either 1(true) or 0(false).
Examples:
#include <stdio.h>
int main(){
int x = 10, y = 12, z = 5;
// check if x is between 5 and 20
printf("x > 5 && x < 20 = %d\n", x > 5 && x < 20);
// check if y is greater than x or divisible by z
printf("y > x || (y %% z == 0) = %d\n", y > x || (y % z == 0));
// see the result of negation of x
printf("!x = %d\n", !x);
return 0;
}
Expected Output:
x > 5 && x < 20 = 1
y > x || (y % z == 0) = 1
!x = 0