Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

#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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading