Home > OS >  Difference between !(n & 1) and n & 1 == 0 in C
Difference between !(n & 1) and n & 1 == 0 in C

Time:04-29

For some reason in C , the expressions if(!(n & 1)) and if(n & 1 == 0) seem to not be equivalent.

Can someone please explain why this happens?

CodePudding user response:

  • if(!(n & 1)) will evaluate to true if the least significant bit of n is 1.

  • if(n & 1 == 0) is equivalent to if(n & (1 == 0)), which will become if (n & 0), which is always false.

Check out the operator precedence table, you will see that == precedes &.

CodePudding user response:

Because of operator precedence. n & 1 == 0 is parsed as n & (1 == 0), not (n & 1) == 0.

  • Related