How "or" / "||" operator works in C++/Cpp ? Does it check all the conditions or it stops as soon as it encounters a condition that is true?

 In C++, the || (logical OR) operator performs short-circuit evaluation. This means that it evaluates conditions from left to right and stops as soon as it encounters a condition that is true. If the left-hand side condition is true, the right-hand side condition is not checked because, for an OR operation, only one true operand is sufficient to yield true.

#include <iostream>
using namespace std;

bool checkA() {
    cout << "Checking A\n";
    return true;
}

bool checkB() {
    cout << "Checking B\n";
    return false;
}

int main() {
    if (checkA() || checkB()) {
        cout << "Result is true\n";
    }
    return 0;
}

Output:

Checking A

Result is true

#include <iostream>
using namespace std;

bool checkA() {
    cout << "Checking A\n";
    return false;
}

bool checkB() {
    cout << "Checking B\n";
    return true;
}

int main() {
    if (checkA() || checkB()) {
        cout << "Result is true\n";
    }
    return 0;
}

Output:

Checking A

Checking B

Result is true


Comments

Popular posts from this blog

The Evolution of Facebook: From Dorm Room to Global Phenomenon

Lakshadweep: Jewel of the Arabian Sea - Unveiling the Serenity of Tropical Paradise