In C++ it’s possible to use a logical operator where a biwise operator was intended:
int unmasked = getUnmasked(); //some wide value
int masked = unmasked & 0xFF; // izolate lowest 8 bits
the second statement could be easily mistyped:
int masked = unmasked && 0xFF; //&& used instead of &
This will cause incorrect behaviour – masked will now be either 0 or 1 when it is inteded to be from 0 to 255. And C++ will not ever complain.
Is is possible to design code in such a way that such errors are detected at compiler level?
Ban in your coding standards the direct use of any bitwise operations in an arbitrary part of the code. Make it mandatory to call a function instead.
So instead of:
You write:
As a bonus, you’ll get a code base which doesn’t have dozens of error prone bitwise operations spread all over it.
Only in one place (the implementation of
GetLowestByteand its sisters) you’ll have the actual bitwise operations. Then you can read these lines two or three times to see if you blew it. Even better, you can unit test that part.