I ran across some code today that was checking a number of error conditions. A single boolean was used all the way through, but instead of reassigning it every time with an =
, it was reassigned with an &=
resulting in a bit wise ANDing of the the previous value of the boolean and the new value. The code looked something like this:
bool result = FirstCheck();
Assert(result);
result &= SecondCheck();
Assert(result);
...
Now I'm curious why someone would do this? This is logically equivalent to just reassigning the value of the boolean as shown by the possible branches below:
- FirstCheck fails (returns false) and program fails on assert and never makes it to SecondCheck
- FirstCheck passes (returns true) and the program makes it to SecondCheck. If SecondCheck returns true, then result is true because true&true = true. If SecondCheck returns false, then result is false becasue true&false = false.
Since there is no logical difference, is there some other reason &=
might be preferable? Or is it more likely that is is a relic of some old code that just never got changed?
EDIT: To clarify, the Assert is always active code. I actually stumbled across this code while investigating a bug because the assert was failing.