Logical operators perform logical operations on Boolean values or expressions. These operators are used to combine two or more conditions and help in decision-making.
Types of Logical OperatorsC++ provides three logical operators:
The logical AND operator returns true only if both operands are true. If any operand is false, the result is false.
The syntax of logical AND is:
condition_1 && condition 22. Logical OR (||)
The logical OR operator returns true if at least one of the conditions is true. If both are false, it returns false.
The syntax of logical OR is:
condition_1 || condition 23. Logical NOT (!)
The logical NOT operator negates the given condition. If a condition is true, it returns false and vice versa.
The syntax of logical NOT is:
!conditionExample of Logical Operators
Try the following example to understand all the logical operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this program.
#include <iostream> using namespace std; main() { int a = 5; int b = 20; int c ; if(a && b) { cout << "Line 1 - Condition is true"<< endl ; } if(a || b) { cout << "Line 2 - Condition is true"<< endl ; } /* Let's change the values of a and b */ a = 0; b = 10; if(a && b) { cout << "Line 3 - Condition is true"<< endl ; } else { cout << "Line 4 - Condition is not true"<< endl ; } if(!(a && b)) { cout << "Line 5 - Condition is true"<< endl ; } return 0; }
When the above code is compiled and executed, it produces the following result −
Line 1 - Condition is true Line 2 - Condition is true Line 4 - Condition is not true Line 5 - Condition is true
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4