In C++, is there any difference between doing && (logical) and & (bitwise) between bool(s)?
bool val1 = foo();
bool val2 = bar();
bool case1 = val1 & val2;
bool case2 = val1 && val2;
Are case1 and case2 identical or if not how exactly do they vary and why would one choose one over the other? Is a bitwise and of bools portable?
The standard guarantees that
falseconverts to zero andtrueconverts to one as integers:So the effect in the example you give is guaranteed to be the same and is 100% portable.
For the case you give, any decent compiler is likely to generate identical (optimal) code.
However, for Boolean expressions
expr1andexpr2, it is not true in general thatexpr1 && expr2is the same asexpr1 & expr2because&&performs “short-circuit” evaluation. That is, ifexpr1evaluates tofalse,expr2will not even be evaluated. This can affect performance (ifexpr2is complicated) and behavior (ifexpr2has side-effects). (But note that the&form can actually be faster if it avoids a conditional branch… Toying with this sort of thing for performance reasons is almost always a bad idea.)So, for the specific example you give, where you load the values into local variables and then operate on them, the behavior is identical and the performance is very likely to be.
In my opinion, unless you are specifically relying on the “short-circuit” behavior, you should choose the formulation that most clearly expresses your intention. So use
&&for logical AND and&for bit-twiddling AND, and any experienced C++ programmer will find your code easy to follow.