Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between if(x^1!=1) and if(int(x^1)!=1) in C++?

I am trying to find if x's first bit from right is 1, so I check if the value of x^1 is 1. However,

int x=6; 
if (x^1!=1) 

gives wrong answer, but

if (int(x^1)!=1) 

gives the correct answer.

I am not sure why. Could someone clarify this for me?

like image 381
Luke Avatar asked Jan 17 '16 21:01

Luke


1 Answers

It's a trap of operator precedence. Operator precedence determines how operations are "grouped" (like how 2*3+4 results in the 2*3 being "grouped" together). Adding parentheses changes how things are "grouped" (for example, 2*(3+4) causes 3+4 to be "grouped" together).

x^1!=1 is equivalent to x^(1!=1), which can be simplified to x^0.

int(x^1)!=1 is equivalent to (x^1)!=1 (because you've manually added parentheses here; the int part isn't very relevant; it's the parentheses that are important).

As you can see, x^(1!=1) and (x^1)!=1 are not the same.

If your goal is to check the first bit, I might suggest using a bitwise-AND (&). You can then just do if (x & 1) (but beware, mixing & and == will result in the same issues as you were having before, so use parentheses if you want to write if ((x & 1) == 1)).

like image 183
Cornstalks Avatar answered Oct 31 '22 03:10

Cornstalks