Logical operators in C++ are used to evaluate relationships between conditions. They return a boolean value, which can either be true
(1) or false
(0). These operators are often combined with comparison operators to build complex decision-making logic.
Logical Operators and Their Functions
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical AND | Returns true if both conditions are true | x > 50 && x < 100 |
|| | Logical OR | Returns true if at least one condition is true | x > 50 || x < 30 |
! | Logical NOT | Reverses the result; returns false if the condition is true | !(x > 50) |
Using Logical Operators Example
#include <iostream> using namespace std; int main() { int bikeSpeed = 120; int carSpeed = 150; // Logical AND if (bikeSpeed > 100 && carSpeed > 140) { cout << "Both bike and car are fast."; } // Logical OR if (bikeSpeed > 130 || carSpeed > 140) { cout << "\nAt least one vehicle is fast."; } // Logical NOT if (!(bikeSpeed > 130)) { cout << "\nThe bike is not exceeding 130 km/h."; } return 0; }
Explanation of the Example
- Logical AND (
&&
):- The first
if
statement checks if bothbikeSpeed
is greater than 100 andcarSpeed
is greater than 140. - If both are true, it prints: “Both bike and car are fast.”
- The first
- Logical OR (
||
):- The second
if
statement evaluates if eitherbikeSpeed
exceeds 130 orcarSpeed
exceeds 140. - If at least one is true, it prints: “At least one vehicle is fast.”
- The second
- Logical NOT (
!
):- The final
if
statement reverses the condition. It checks ifbikeSpeed
is not greater than 130. - If true, it prints: “The bike is not exceeding 130 km/h.”
- The final