Using bitwise operators for Booleans in C++

|| and && are boolean operators and the built-in ones are guaranteed to return either true or false. Nothing else.

|, & and ^ are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn’t want. For instance:

BOOL two = 2;
BOOL one = 1;
BOOL and = two & one;   //and = 0
BOOL cand = two && one; //cand = 1

In C++, however, the bool type is guaranteed to be only either a true or a false (which convert implicitly to respectively 1 and 0), so it’s less of a worry from this stance, but the fact that people aren’t used to seeing such things in code makes a good argument for not doing it. Just say b = b && x and be done with it.

Leave a Comment