Logical Operators in C++

Logical operators are used to combine multiple Boolean expressions or values and provide a single Boolean output. They are essential in controlling program flow.

Key Topics

List of Logical Operators

Operator Description Example
&& Logical AND a > b && c > d
|| Logical OR a > b || c > d
! Logical NOT !(a > b)

Examples

Example: Using Logical Operators

#include <iostream>

int main() {
    int age = 25;
    bool hasLicense = true;
    
    if (age >= 18 && hasLicense) {
        std::cout << "Eligible to drive." << std::endl;
    } else {
        std::cout << "Not eligible to drive." << std::endl;
    }
    
    bool isStudent = false;
    if (!isStudent || age >= 21) {
        std::cout << "Eligible for membership." << std::endl;
    }
    
    return 0;
}

Output:

Eligible to drive.

Eligible for membership.

Explanation: The program uses logical operators to determine eligibility based on certain conditions involving age, hasLicense, and isStudent.

Key Takeaways

  • Logical operators combine multiple Boolean expressions.
  • && (AND) returns true if both operands are true.
  • || (OR) returns true if at least one operand is true.
  • ! (NOT) inverts the Boolean value.