How if(x & y) condition works in c++ [closed]

With x & 5 you are making a bitwise and operation (it is not a logical and). Since:

4 = 0b0100 AND
5 = 0b0101 =
4 = 0b0100 != 0

the result of the condition is true. That 4 is less or equal of 5 (4 <= 5) is again true.
But you are not testing the same condition, you are only comparing two operations that both return true. It is only by chance that both return true.

Don’t worry: this is a mistake that many people that just started programming make. Please check out the differences between bitwise operations and logical connectives.

Leave a Comment