clanguage-lawyerundefined-behavior

Is left shifting a long long considered Undefined Behavior in C?


I know that the following code in C:

(1 << 31)

is considered Undefined Behavior due to the C standard (6.5.3 Shift Operators):

The result of the shift operation is undefined if the right operand is negative or if its value is greater than the number of bits in an int.

I’m just curious whether following C code:

(1LL << 63)

is also considered Undefined Behavior in any of the C standards.


Solution

  • C23 Section 6.5.7 says (my emphasis):

    The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2ᴱ², wrapped around. If E1 has a signed type and nonnegative value, and E1 × 2ᴱ² is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

    So if your platform's long long can represent 2⁶³, you're fine. Since one bit must be used to indicate its sign, that means 1LL << 63 is UB if long long has 64 bits.

    (long long cannot be smaller than 64 bits, but may be wider).