Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one use the |= operator on a boolean value in C#?

Tags:

c#

boolean

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;    
like image 878
carny666 Avatar asked Mar 28 '12 14:03

carny666


People also ask

What is the |= operator in C++?

|= is the bitwise OR as you point out. So x |= 1 is the same as doing x = x | 1.

How do Booleans work in C?

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.

What is Boolean condition in C?

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.

What can I use instead of Boolean in C?

Though C doesn't support Boolean value. But we can use Logical Operators like '&&', '||' or '!


2 Answers

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;.

like image 184
Ry- Avatar answered Sep 24 '22 03:09

Ry-


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.

like image 43
phoog Avatar answered Sep 22 '22 03:09

phoog