C++ Logical Operators

Logical operators in C++ are used to combine multiple conditions or to reverse the logic of a condition. They are commonly used in if statements, loops, and boolean expressions.

List of Logical Operators

OperatorDescriptionExample
&&Logical AND – True if both operands are true(a > 0 && b > 0)
||Logical OR – True if at least one operand is true(a > 0 || b > 0)
!Logical NOT – Reverses the truth value of an operand!(a > 0)

Example Program

#include <iostream>
using namespace std;

int main() {

    int a = 5;
    int b = 10;

    // Logical AND
    if(a > 0 && b > 0) {
        cout << "Both a and b are positive" << endl;
    }

    // Logical OR
    if(a < 0 || b > 0) {
        cout << "At least one condition is true" << endl;
    }

    // Logical NOT
    if(!(a < 0)) {
        cout << "a is not negative" << endl;
    }

    return 0;
}

Output

Both a and b are positive
At least one condition is true
a is not negative

Important Notes

  • Logical operators always return true (1) or false (0).
  • && has higher precedence than ||, so use parentheses to ensure correct evaluation.
  • Logical operators are often combined with comparison operators to create complex conditions.

Next Topic

Next, learn about C++ Bitwise Operators.