clanguage-lawyerstandardsundefined-behavior

Is shifting 0 to the left considered undefined behavior in C?


Is either of these expressions Undefined Behavior (UB)?

  1. 0 << 32
  2. 0LL << 64

I would appreciate it if the answer includes references to the C standard.


Solution

  • Refer to ISO C Standard (ISO/IEC 9899), 6.5.7 Bitwise shift operators, paragraph 3:

    The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

    Assuming the common configuration of 32-bit int and 64-bit long long:

    Analyze 0 << 32 expression: the right operand is the integer constant 32, the value is equal to the width of the left operand (int). So the behavior is undefined.

    Analyze 0LL << 64 expression: the right operand is the integer constant 64, the value is also equal to the width of the left operand (long long). So the behavior is also undefined.

    Both 0 << 32 and 0LL << 64 result in undefined behavior (UB) in C.