Skillversitas

C++ Relational and Logical Operators

Relational operators are used to compare two values and produce a boolean value (true or false). Logical operators are used to combine multiple boolean conditions into a single logical expression. Both types of operators are very important in decision making and program flow control.

In C++, boolean values are represented as integers: true has the value 1 and false has the value 0. Relational and logical operators form the foundation of control statements such as if, while, and for.

Relational Operators

Operator Name Description
== Equal to Check whether two values are equal
!= Not equal to Check whether two values are different
> Greater than Check whether the left value is greater
< Less than Check whether the left value is smaller
>= Greater than or equal to Check whether the left value is greater than or equal
<= Less than or equal to Check whether the left value is less than or equal

Logical Operators

Operator Name Description
&& Logical AND True if both conditions are true
\|\| Logical OR True if either condition is true
! Logical NOT Inverts a boolean value

Code Example

#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20, c = 10;

    // Relational operators
    cout << "=== Relational Operators ===" << endl;
    cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
    cout << "a == c : " << (a == c) << endl;
    cout << "a != b : " << (a != b) << endl;
    cout << "a > b  : " << (a > b) << endl;
    cout << "a < b  : " << (a < b) << endl;
    cout << "a >= c : " << (a >= c) << endl;
    cout << "a <= b : " << (a <= b) << endl;

    // Logical operators
    cout << "\n=== Logical Operators ===" << endl;
    bool x = true, y = false;
    cout << "x = " << x << ", y = " << y << endl;
    cout << "x && y : " << (x && y) << endl;
    cout << "x || y : " << (x || y) << endl;
    cout << "!x     : " << (!x) << endl;
    cout << "!y     : " << (!y) << endl;

    // Combining relational and logical
    cout << "\n=== Operator Combination ===" << endl;
    int age = 25;
    bool hasIDCard = true;

    bool canVote = (age >= 17) && hasIDCard;
    cout << "Age: " << age << ", Has ID card: " << hasIDCard << endl;
    cout << "Can vote: " << canVote << endl;

    // Short-circuit evaluation
    cout << "\n=== Short-Circuit Evaluation ===" << endl;
    int value = 0;

    // If the first condition is false, the second condition is not evaluated
    if (value != 0 && 10 / value > 1) {
        cout << "Condition met" << endl;
    } else {
        cout << "Short-circuit prevents division by zero" << endl;
    }

    // Demonstration of evaluation order
    int p = 5, q = 0;
    cout << "\np = " << p << ", q = " << q << endl;

    // In OR, if the first condition is true, the second condition is not evaluated
    if (p > 0 || q > 0) {
        cout << "p > 0 is already true, q > 0 is not evaluated" << endl;
    }

    // In AND, if the first condition is false, the second condition is not evaluated
    if (p < 0 && q > 0) {
        cout << "This will not be printed" << endl;
    } else {
        cout << "p < 0 is already false, q > 0 is not evaluated" << endl;
    }

    // Operator NOT
    cout << "\n=== Operator NOT ===" << endl;
    bool active = true;
    bool notActive = !active;
    cout << "active: " << active << ", !active: " << notActive << endl;

    int value2 = 0;
    cout << "value2: " << value2 << ", !value2: " << !value2 << endl;

    return 0;
}

Code Explanation

  • Relational Operators: Produce 1 (true) or 0 (false). Note that == is an equality check, different from =, which is an assignment.
  • AND Operator (&&): Produces true only if both operands are true. If either one is false, the result is false.
  • OR Operator (||): Produces true if either or both operands are true.
  • NOT Operator (!): Inverts a boolean value. !true becomes false, !false becomes true. For integers, !0 has the value 1 and !otherValue has the value 0.
  • Short-Circuit Evaluation: C++ uses shortcut evaluation. In &&, if the first condition is false, the second condition is not evaluated. In ||, if the first condition is true, the second condition is not evaluated. This is useful for preventing errors such as division by zero.

Everyday Use Cases

Authentication System:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string username, password;
    int attempt = 0;
    int maxAttempts = 3;

    cout << "=== Login System ===" << endl;

    while (attempt < maxAttempts) {
        cout << "\nAttempt " << (attempt + 1) << " of " << maxAttempts << endl;
        cout << "Username: ";
        cin >> username;
        cout << "Password: ";
        cin >> password;

        // Validate empty input
        bool usernameValid = (username.length() > 0);
        bool passwordValid = (password.length() >= 4);

        if (!usernameValid) {
            cout << "Username cannot be empty!" << endl;
        } else if (!passwordValid) {
            cout << "Password must be at least 4 characters!" << endl;
        } else if (username == "admin" && password == "1234") {
            cout << "Login successful! Welcome, " << username << "!" << endl;
            return 0;
        } else {
            cout << "Wrong username or password!" << endl;
        }

        attempt++;
    }

    cout << "\nAccount locked after " << maxAttempts << " failed attempts." << endl;
    return 1;
}

Value Range Check:

#include <iostream>
using namespace std;

int main() {
    int score;

    cout << "Enter the exam score (0-100): ";
    cin >> score;

    // Validate the range
    bool validRange = (score >= 0) && (score <= 100);

    if (!validRange) {
        cout << "Error: The score must be between 0 and 100!" << endl;
        return 1;
    }

    // Determine the grade
    char grade;
    if (score >= 85 && score <= 100) {
        grade = 'A';
    } else if (score >= 70 && score < 85) {
        grade = 'B';
    } else if (score >= 55 && score < 70) {
        grade = 'C';
    } else if (score >= 40 && score < 55) {
        grade = 'D';
    } else {
        grade = 'F';
    }

    cout << "Score: " << score << " | Grade: " << grade << endl;

    // Check passing status
    bool passed = (score >= 55);
    cout << "Status: " << (passed ? "PASSED" : "FAILED") << endl;

    return 0;
}

Conclusion

Relational operators (==, !=, >, <, >=, <=) produce boolean values from comparing two values. Logical operators (&&, ||, !) combine boolean conditions. Short-circuit evaluation in && and || provides extra optimization and safety by evaluating operands only when necessary. The combination of these operators forms the basis of all decision-making logic in a C++ program.