Pádraig Brady <p...@draigbrady.com> writes:

> As well as being distracting, bitwise operators are
> not short circuiting and brittle with C89 where
> bool can be an int, i.e. > 1.

I don't find them distracting; on the contrary, I find them a helpful
reminder that the expressions are boolean (in the traditional
mathematical sense) and so I don't need to worry about the
complexities of short-circuit evaluation.

Also, the conditional branches generated by short-circuit operators
can make code harder to debug because GDB starts jumping all over the
place when I single step.

Furthermore, bitwise operators often generate shorter and faster code,
particularly on modern processors where conditional branches are far
more expensive than logical operations.  For example, consider these
functions:

bool F (bool a, bool b, bool c, bool d) { return a && b && c && d; }
bool G (bool a, bool b, bool c, bool d) { return a & b & c & d; }

For F, gcc -O2 (x86) currently generates 3 conditional branches
(ouch!); for G it generates straightline code (good with pipelining).
F is also quite a bit bigger than G (20 instructions vs 12; and 49
bytes versus 30), and this size increase bloats the code and causes
more instruction cache misses.

Bitwise operators are equivalent in behavior to short-circuit
operations on boolean expressions (i.e., expressions involving just 0
and 1) that do not have side effects or conditionally-undefined
behavior. This is true regardless of whether the boolean type is
implemented via 'int'.  Let's just leave them alone.


Reply via email to