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?
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.
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 )
因为if ( status &= Class1 )
会将0分配给状态,所以在所有下一个条件中,status的值将为0,这样就不会执行任何条件,并且不会增加conter的值。
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.