Why simple code doesn`t work corectly c++?

Viewed 81
#include <iostream>
bool check_number(unsigned short int a, unsigned short int b) {
    if ((a || b == 30) || a + b == 30) {
        return true;
    }
    return false;
}

int main() {
    
    std::cout << check_number(15, 16) << std::endl;
    std::cin.get();
    return 0;
}

Why I get "true" result? Why not false, we know that 15 + 16 is 31

1 Answers

if ((a || b == 30) is not "either a or b equal 30" it is "either (a) or (b equals 30)". As a is non-zero it is true when converted to bool.

So you have

if ((true || other condition) || just_another_condition) 

and because || is short-circuiting the condition as a whole is true.

If you actually wanted "either a equals 30 or b equals 30" that is (a == 30) || (b == 30).

Last but not least, if you have code like this:

if (condition) {
     return true;
} else { 
     return false;
}

Then this is just return condition;

Related