In chapter 2, the section on bitwise operators (section 2.9), I\'m having trouble understanding how one of the sample methods works.
Here\'s the method provided:
Nobody mentioned it yet, but in ANSI C ~0 << n causes undefined behaviour.
This is because ~0 is a negative number and left-shifting negative numbers is undefined.
Reference: C11 6.5.7/4 (earlier versions had similar text)
The result of
E1 << E2isE1left-shiftedE2bit positions; vacated bits are filled with zeros. [...] If E1 has a signed type and nonnegative value, andE1×2E2is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
In K&R C this code would have relied on the particular class of system that K&R developed on, naively shifting 1 bits off the left when performing left-shift of a signed number (and this code also relies on 2's complement representation), but some other systems don't share those properties so the C standardization process did not define this behaviour.
So this example is really only interesting as a historical curiosity, it should not be used in any real code since 1989 (if not earlier).