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:
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.
You're assuming the assertions are enabled. If this is using Debug.Assert
, the method will only actually be called if the DEBUG
conditional compilation symbol is defined.
Assuming result
is used later on (beyond the assertion) then there's a difference when FirstCheck()
returns false
.
See more on this question at Stackoverflow