Example:
We found this is some vendor written code and we're trying to figure out why they'd do this.
bool tmp = false; if (somecase) tmp = true; if (someOtherCase) tmp |= true;
|= is the bitwise OR as you point out. So x |= 1 is the same as doing x = x | 1.
C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1.
Though C doesn't support Boolean value. But we can use Logical Operators like '&&', '||' or '!
For no good reason at all. A boolean value |= true
will always be true
. This is someone trying to be fancy, or forgetting boolean logic =)
Change it to tmp = true;
.
Perhaps one of the boolean literals used to be a variable, and they just didn't think to change the operator when they changed the operand. Obviously the logic is equivalent.
More likely, they were thinking that in the second case, they want to retain the result of evaluating the first "if" condition. Of course, that's false reasoning.
A simpler equivalent statement:
bool tmp = somecase | someOtherCase;
EDIT
As pickypg notes, this statement could be confusing, since most people don't expect |
with boolean values, and many won't notice it, or won't think about the implications for side effects. The best way to be explicit (if indeed there are side effects) would be minitech's solution: just change the |=
to =
.
Or, if there are no side effects to the someOtherCase
expression, use Jakub Konecki's solution : someCase || someOtherCase
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With