Search code examples
c++coding-stylestandards-compliance

behavior of bool with non-boolean operators


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.


Solution

  • According to 4.7 (Integral conversions), paragraph 4, "If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one." In 4.12, "An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true."

    In a context where bool operands are not allowed but integral operands are, the bool will be converted to an integral type. When the integer result is stored in a bool variable, it will be converted to bool.

    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 false if all three variables are true. ((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.