Read Time:3 Minute, 3 Second
Logical operators are used to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.
Operator | Example | Meaning |
---|---|---|
&& | expression1 && expression2 | Logical AND. True only if all the operands are true. |
|| | expression1 || expression2 | Logical OR. True if at least one of the operands is true. |
! | !expression | Logical NOT. True only if the operand is false. |
In C++, logical operators are commonly used in decision making. To further understand the logical operators, let’s see the following examples,
Suppose, a = 5 b = 8 Then, (a > 3) && (b > 5) evaluates to true (a > 3) && (b < 5) evaluates to false (a > 3) || (b > 5) evaluates to true (a > 3) || (b < 5) evaluates to true (a < 3) || (b < 5) evaluates to false !(a < 3) evaluates to true !(a > 3) evaluates to false
Example: Logical Operators
#include <iostream> using namespace std; int main() { bool result; result = (3 != 5) && (3 < 5); // true cout << "(3 != 5) && (3 < 5) is " << result << endl; result = (3 == 5) && (3 < 5); // false cout << "(3 == 5) && (3 < 5) is " << result << endl; result = (3 == 5) && (3 > 5); // false cout << "(3 == 5) && (3 > 5) is " << result << endl; result = (3 != 5) || (3 < 5); // true cout << "(3 != 5) || (3 < 5) is " << result << endl; result = (3 != 5) || (3 > 5); // true cout << "(3 != 5) || (3 > 5) is " << result << endl; result = (3 == 5) || (3 > 5); // false cout << "(3 == 5) || (3 > 5) is " << result << endl; result = !(5 == 2); // true cout << "!(5 == 2) is " << result << endl; result = !(5 == 5); // false cout << "!(5 == 5) is " << result << endl; return 0; };
Output
(3 != 5) && (3 < 5) is 1 (3 == 5) && (3 < 5) is 0 (3 == 5) && (3 > 5) is 0 (3 != 5) || (3 < 5) is 1 (3 != 5) || (3 > 5) is 1 (3 == 5) || (3 > 5) is 0 !(5 == 2) is 1 !(5 == 5) is 0
Explanation of logical operator program
(3 != 5) && (3 < 5)
evaluates to 1 because both operands(3 != 5)
and(3 < 5)
are 1 (true).(3 == 5) && (3 < 5)
evaluates to 0 because the operand(3 == 5)
is 0 (false).(3 == 5) && (3 > 5)
evaluates to 0 because both operands(3 == 5)
and(3 > 5)
are 0 (false).(3 != 5) || (3 < 5)
evaluates to 1 because both operands(3 != 5)
and(3 < 5)
are 1 (true).(3 != 5) || (3 > 5)
evaluates to 1 because the operand(3 != 5)
is 1 (true).(3 == 5) || (3 > 5)
evaluates to 0 because both operands(3 == 5)
and(3 > 5)
are 0 (false).!(5 == 2)
evaluates to 1 because the operand(5 == 2)
is 0 (false).!(5 == 5)
evaluates to 0 because the operand(5 == 5)
is 1 (true).
[…] Logical Operators […]