Introducing to C Logical Opeartors
You use C logical operators to connect expressions and / or variables to form compound conditions. The C logical expression return an integer (int). The result has value 1 if the expression is evaluated to true otherwise it return 0. C uses the following symbols for the boolean operations AND, OR ,and NOT.
Operator | Meaning |
---|---|
&& | logical AND |
|| | logical OR |
! | logical NOT |
The AND operator (&&) and OR operator (||) has essential peculiarity:
- The || operator, their operands are evaluated in order from left to right, and if the value of the left operand is sufficient to determine the result of the operation, then the right operand is not evaluated at all.
- The operator && evaluates the right operand only if the left operand yields 1;
The following table illustrates the truth table of the logical operators:
a | b | a&&b | a||b | !a |
---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True | True |
False | False | False | False | True |
Example of C Logical Operators
The following program illustrate the C logical operators:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int x = 10; int y = 15;int z = 20;
if (x < y && y < z) {
printf("x > y && y < z\n");
}if (x > y || y < z) {
printf("x > y || y < z\n");
}
if (!(x > y)) {
printf("!(x > y)\n");
}
return (0);
}
Below is the output of the C logical operators demo program:
x > y && y < z x > y || y < z !(x > y)
0 Comments