What I really want is a ||= operator.
old_value = old_value || possible_new_value;
old_value ||= possible_new_value;
The second line is a compiler error (c++ doesn’t have a ||= operator).
So what are my other options?
old_value += possible_new_value;
old_value |= possible_new_value;
While I’m on the subject how does bool behave with other non-boolean operators?
-
-=
&
&=
...
I can verify these empirically, but I’m most interested in what the standard says.
According to 4.7 (Integral conversions), paragraph 4, “If the destination type is
bool, see 4.12. If the source type isbool, the valuefalseis converted to zero and the valuetrueis converted to one.” In 4.12, “An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of typebool. A zero value, null pointer value, or null member pointer value is converted tofalse; any other value is converted totrue.”In a context where
booloperands are not allowed but integral operands are, theboolwill be converted to an integral type. When the integer result is stored in aboolvariable, it will be converted tobool.Therefore, you will be able to use + and * as boolean or and and, and you can use | and & also. You can’t get away with mixing them, as (bool1 + bool2) & bool3 will yield
falseif all three variables aretrue. ((1 + 1) & 1 is 2 & 1, which is 0, or false.)Remember that | and || don’t work identically even here. | will evaluate both sides, and then evaluate the bitwise or. || will evaluate the first operand, then only if that was false will evaluate the second.
I’m not going to discuss the stylistic issues here, but if I did anything like that I’d be sure to comment it so people knew what I was doing and why.