Kache Kache - 25 days ago 16
C++ Question

Why doesn't c++ have &&= or ||= for booleans?

Is there a "very bad thing" that can happen &&= and ||= were used as syntactic sugar for

bool foo = foo && bar
and
bool foo = foo || bar
?

Answer

A bool may only be true or false in C++. As such, using &= and |= is perfectly safe (even though I don’t particularly like the notation). True, they will perform bit operations rather than logical operations (and as such, they won’t short-circuit) but these bit operations follow a well-defined mapping, which is effectively equivalent to the logical operations, as long as both operands are indeed of type bool.1

Contrary to what other people have said here, a bool in C++ must never have a different value such as 2. When assigning that value to a bool, it will be converted to true as per the standard.

The only way to get an invalid value into a bool is by using reinterpret_cast on pointers:

int i = 2;
bool b = *reinterpret_cast<bool*>(&i);
b |= true; // MAY yield 3 (but doesn’t on my PC!)

But since this code results in undefined behaviour anyway, we may safely ignore this potential problem in conforming C++ code.


1 Admittedly this is a rather big caveat as Angew’s comment illustrates:

bool b = true;
b &= 2; // yields `false`.

The reason is that b & 2 performs integer promotion such that the expression is then equivalent to static_cast<int>(b) & 2, which results in 0, which is then converted back into a bool. So it’s true that the existence of an operator &&= would improve type safety.

Comments