Why doesn't c++ have &&= or ||= for booleans? -
is there "very bad thing" can happen &&= , ||= used syntactic sugar bool foo = foo && bar
, bool foo = foo || bar
?
a bool
may true
or false
in c++. such, using &=
, |=
safe (even though don’t particularly notation). true, will perform bit operations rather logical operations (and such, won’t short-circuit) these bit operations follow well-defined mapping, equivalent logical operations, as long as both operands are indeed of type bool
.1
contrary other people have said here, bool
in c++ must never have different value such 2
. when assigning value bool
, converted true
per standard.
the way invalid value bool
using reinterpret_cast
on pointers:
int = 2; bool b = *reinterpret_cast<bool*>(&i); b |= true; // may yield 3 (but doesn’t on pc!)
but since code results in undefined behaviour anyway, may safely ignore potential problem in conforming c++ code.
1 admittedly rather big caveat angew’s comment illustrates:
bool b = true; b &= 2; // yields `false`.
the reason b & 2
performs integer promotion such expression equivalent static_cast<int>(b) & 2
, results in 0
, converted bool
. it’s true existence of operator &&=
improve type safety.
Comments
Post a Comment