mahmood
mahmood

Reputation: 24795

bitwise AND in C++

I have defined an enum like this:

enum blStatus {
   Class1 = 0x40,           /* 0000,0100,0000 */
   Class2 = 0x80,           /* 0000,1000,0000 */
   Class3 = 0x100,          /* 0001,0000,0000 */
   Class4 = 0x200           /* 0010,0000,0000 */
}

Now, somewhere in the code I have:

 if ( status &= Class1 )
   ++c1;
 else if ( status &= Class2 )
   ++c2;
 else if ( status &= Class3 )
   ++c3;
 else if ( status &= Class4 )
   ++c4;

Assume, the status hat this value:

 status = 143   /* 0000,1000,1111 */

While debugging, none of the conditions is true. However "status &= Class2" is:

 0000,1000,1111 & 0000,1000,0000 = 0000,1000,0000

and the c2 counter must be incremented. but while debugging, all conditions are passed (ignored) and no counter increment. Why?

Upvotes: 2

Views: 205

Answers (4)

Andrii
Andrii

Reputation: 1906

Operator &= puts computation result into left operand (equals a = a & b). After computation the expression (status &= Class1) the status variable is 0 and all following conditions are FALSE.

Upvotes: 0

Hemant Metalia
Hemant Metalia

Reputation: 30688

because if ( status &= Class1 ) will assign 0 to status so in all next conditions value of status will 0 so none of the condition will be executed and non of the conter incremented.

Upvotes: 1

nsanders
nsanders

Reputation: 12656

Use & instead of &=.

When you do x &= y you are getting:

 x = x & y;

What you really want in your code:

if ( status & Class1 )

Now, after each if clause, you leave the value of status untouched.

Upvotes: 7

codaddict
codaddict

Reputation: 455370

This is because you are changing the status in:

if ( status &= Class1 )

status &= Class1 is same as status = status & Class1 as a result status changes to 0:

status = 0000 1000 1111
Class1 = 0000 0100 0000  &
-----------------------
status = 0000 0000 0000

Since you intend to just check the bits you don't need to do an assignment:

if ( status & Class1 )

Upvotes: 4

Related Questions