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
?
views:
352answers:
2A 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
.
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.
&&
and &
have different semantics: &&
will not evaluate the second operand if the first operand is false
. i.e. something like
flag = (ptr != NULL) && (ptr->member > 3);
is safe, but
flag = (ptr != NULL) & (ptr->member > 3);
is not, although both operands are of type bool
.
The same is true for &=
and |=
:
flag = CheckFileExists();
flag = flag && CheckFileReadable();
flag = flag && CheckFileContents();
will behave differently than:
flag = CheckFileExists();
flag &= CheckFileReadable();
flag &= CheckFileContents();