We have equivalent assignment operators for all Logical operators, Shift operators, Additive operators and all Multiplicative operators.
Why did the logical operators get left out? Is there a good technical reason why it is hard?
The result of a logical OR ( || operator in C) is true if EITHER of its inputs is true. Similarly logical AND ( && operator in C) is true if BOTH of its inputs are true.
The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int .
|= just assigns the bitwise OR of a variable with another to the one on the LHS.
a ||= b is a conditional assignment operator. It means: if a is undefined or falsey, then evaluate b and set a to the result. Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.
Why did the logical operators get left out? Is there a good technical reason why it is hard?
They didn't. You can do &=
or |=
or ^=
if you want.
bool b1 = false; bool b2 = true; b1 |= b2; // means b1 = b1 | b2
The ||
and &&
operators do not have a compound form because frankly, they're a bit silly. Under what circumstances would you want to say
b1 ||= b2; b1 &&= b2;
such that the right hand side is not evaluated if the left hand side does not change? It seems like only a few people would actually use this feature, so why put it in?
For more information about the compound operators, see my serious article here:
https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-one
and the follow-up April-Fools article here:
https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two
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