Peculiar Behaviour of Bitwise Operators

Правка en1, от singlabharat, 2021-09-14 09:42:05

Hello CF!

Let me ask you, what is 3 & 6 (where & is the bitwise AND operator)? You'll answer 2, right? Well, I wrote this piece of code (don't remember why)

if (3 & 6 == 2) cout << "Equal";
else cout << "Not Equal";

...and the output is

Spoiler

What in this universe happened??? Though this might seem obvious to some, it potentially could cost you a whole problem... Let me briefly explain the "why" so you don't make the same error I made.

The reason is Operator Precedence Counter-intuitively, operators like &, ^, | should all have a higher precedence than == in C++, turns out this is not the case! Have a look here: C++ Operator Precedence

Thus the above code actually is if (3 & (6 == 2)) which is if (0)

So, the takeaway is to always wrap bitwise operations in parenthesis to avoid such mistakes. Here's the correct code, which gives the desired output "Equal

if ((3 & 6) == 2) cout << "Equal";
else cout << "Not Equal";

Hope this helps and thanks for reading till the end... and you know what to do when you reach this far :P

Теги #bitwise, #c++

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский singlabharat 2021-09-14 09:56:07 154 Tiny change: 'operator)?\\\nYou'll' -> 'operator)? \\\nYou'll' (published)
en1 Английский singlabharat 2021-09-14 09:42:05 1332 Initial revision (saved to drafts)