Need help understanding “getbits()” method in Chapter 2 of K&R C

后端 未结 6 1078
暗喜
暗喜 2020-12-04 16:03

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:

6条回答
  •  旧巷少年郎
    2020-12-04 16:22

    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 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. [...] If E1 has a signed type and nonnegative value, and E1 × 2E2 is 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).

提交回复
热议问题