9

Why does the expression n&1 == 0 always return false, where n is an integer?

I want to use bitwise operation to determine whether n is even. However, it always return false. (The clion also prompted me that it always returns false).

What's more, it works when I use n&1 != 0 to determine whether n is odd.

phuclv
  • 37,963
  • 15
  • 156
  • 475
JunGor
  • 423
  • 4
  • 10
  • 4
    http://en.cppreference.com/w/cpp/language/operator_precedence – Benjamin Lindley Apr 16 '16 at 02:51
  • 1
    If `(n & 1) == false` then it's even number and odd otherwise. In g++, compile with `-Wall` option so that it will give you warning for `n & 1 == 0` for putting braces around. – iammilind Apr 16 '16 at 02:52
  • the way you have it looks like `n&(1==0)` so since `1==0` is always 0 we get `n&0` which is always 0 – TheQAGuy Apr 16 '16 at 02:53
  • This has no relation to IDE whatsoever. It's because of the C standard. To determine if a number is odd, just `if (n & 1)` is enough. But better use [`n % 2 == 1`](http://stackoverflow.com/q/10681375/995714) – phuclv Apr 16 '16 at 03:29

1 Answers1

19

Its because of the operator precedence.

== has higher precedence than the & operator, so 1 == 0 gets evaluated first to 0. Then the bit wise AND is performed which ultimately returns false.

QuikProBroNa
  • 796
  • 2
  • 7
  • 25