views:

352

answers:

2

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?

+4  A: 

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.

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.

Konrad Rudolph
dan04
nikie
Konrad Rudolph
In fact, if you try to do a `switch` on the above `b`, it is likely you end up in `default:` even if you have both true and false branches.
Johannes Schaub - litb
@Johannes: The UB case? Yes, that’s possible. But I’ve tested this and on my PC (OS X 10.5, GCC 4.4.2) it actually doesn’t – which kind of surprised me, too.
Konrad Rudolph
+11  A: 

&& 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();
nikie
Kache4
+1 Brilliant idea.
Pavel Radzivilovsky