0
#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

  • 4
    First thought: because I don't think you understand what `if ((a || b == 30) || a + b == 30)` is actually doing. Boolean logic in C++ is highly elaborative. If you want to do "a or b is 30" you need to elaborate to "a is 30 or b is 30" and *then* translate to code: `(a == 30) || (b == 30)` – WhozCraig Sep 12 '22 at 18:34
  • 6
    `(a || b == 30)` is the same as `(a != 0 || b == 30)` – Eljay Sep 12 '22 at 18:35
  • 6
    Unrelated: the code `if (‹condition›) return true; return false;` is unnecessarily convoluted: it can (and should!) be shortened to `return ‹condition›;`. – Konrad Rudolph Sep 12 '22 at 18:35
  • 2
    @SadlyFullStack: easy: `return\n(\n(\na\n||\nb\n==\n30\n)\n||\na\n+\nb\n==\n30\n)\n;` – prapin Sep 12 '22 at 18:38
  • 1
    @SadlyFullStack Getting paid per line of code, and/or per bug fixed is the absolute Mecca of engineering jobs. If you're getting even half of that you're already ahead of the game. Wally says: "Gonna go write me a new mini-van". – WhozCraig Sep 12 '22 at 18:41
  • 2
    btw 3 conditions in a single line is not what I call "simple". And I am not being sarcastic. If you had each condition on a seperate line then watching them with a debugger is much simpler. (And if you are actually payed by lines of code it pays off double ;) – 463035818_is_not_an_ai Sep 12 '22 at 18:41
  • The vast majority of the time, trust the compiler and write code that is utterly stupid. Stuff that can be understood by a kid who can read Dr. Seuss. Then build these stupid, simple bits of code into more complicated stuff. Code describes program behaviour. A compiler will take this described behaviour and turn it into a fast program for you. Sometimes the stupider you write, the faster the program because the compiler can understand what you really meant to do. And sometimes you **do** need to get tricky, but make the compiler tell you you have to get fancy to get the results you need. – user4581301 Sep 12 '22 at 18:49

1 Answers1

7

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;

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185