singlabharat's blog

By singlabharat, history, 3 years ago, In English

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

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!

  • Vote: I like it
  • +38
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it +24 Vote: I do not like it

Modern compilers will warn you about that. I personally compile all my code with -Wall -Wextra -Wshadow. I also recommend adding -Werror so it's impossible to ignore warnings.

#include <iostream>
using namespace std;
int main() {
    if (3 & 6 == 2) cout << "Equal";
    else cout << "Not Equal";
}

g++'s output:

a.cpp: In function 'int main()':
a.cpp:4:15: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses]
    4 |     if (3 & 6 == 2) cout << "Equal";
      |             ~~^~~~
  • »
    »
    3 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Wow, thanks for adding! I'll compile with them from now on too

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I have had this bug in my code before and tbh debugging is a nightmare.