C++ gotcha: test bool against bit logic

Alec Jacobson

January 09, 2013

weblog/

I tried to do:
bool v;
...
if( v != (my_bits & MASK) )
{
  my_bits ^= MASK;
}
and was surprised to find out that this failed to do what I expected it to: if the truth of v matches the truth of the statement (my_bits masked with MASK) then toggle my_bits according to MASK. I guess the root of the problem is that bool is not really a byte, so I'm not comparing true/false to true/false, but rather [bit expression for zero]/[bit expression for one] to (my_bits & MASK). My fix was to change the if statement to:
if(v != (0!=(my_bits & MASK))
which at least semantically still makes sense.