Take the 2-minute tour ×

I am operating on individual bits of two integers, (i am using g++ for compilation on Ubuntu machine).

In some intermediate step, I have the bit representations as

q = 11000000000000000000000000000000
q_1 = 00000000000000000000000000000001

Now I want to check whether unit's places of q and q_1 are both same or not. so, I am checking (*q)&1==q_1 in the if condition, and its working fine.

But whenever I want to check that unit's place of q is 0 and that of q_1 is 1, I thought I should do ((*q)&1==0) && (q_1==1), but it is not working out as expected. For debugging, I cout ed the values of ((*q)&1==0) and (q_1==1) individually and they got printed as 1. However, the value of ((*q)&1==0) && (q_1==1) got printed as 0. Why?

*EDIT : * In the function, q was passed by reference, so I am using *q to get the value..

share|improve this question
About your EDIT: you mean, passed as pointer? If it was passed as reference, then you wouldn't use the *. –  hyde Feb 1 '13 at 11:47
This is such a classic bug that a minimum of research would give you the cause: bitwise & has lower operator precedence than ==. As a rule of thumb: if you don't know all of the operator precedence rules in detail, then use a parenthesis. –  Lundin Feb 1 '13 at 11:48
sorry for that, I already used a lot of parenthesis around (*q) because of not knowing the precedence, got confused because both the operands of & were 1 and still I was getting 0 as output... –  Shaarad Dalvi Feb 1 '13 at 11:51
@hyde, yes, passed as pointer...the function definition says void func(int *q,int*m) –  Shaarad Dalvi Feb 1 '13 at 11:52
Always use parentheses around bit operators. Their precedence is either not what you would naturally expect (&, ^, | are on the wrong side of comparison operators, probably because they were confounded with logical operators), or unclear (<<, >>). –  starblue Feb 2 '13 at 9:02
add comment

1 Answer

up vote 11 down vote accepted

In C and C++, the bitwise & operator actually has lower precedence than the equivalence operator ==. You'll need to wrap your bitwise operators in parentheses.



should be:

(((*q)&1)==0) && (q_1==1)

See: http://en.cppreference.com/w/cpp/language/operator_precedence

share|improve this answer
Also (*q&1)==0 && q_1==1 would be just enough. –  ybungalobill Feb 1 '13 at 11:46
add comment

Your Answer


