9

This question was asked in an interview.

What is the reason that left shift << of a negative value has undefined behavior, while Right shift >> of a negative signed number has implementation-defined behavior?

C11 $6.5.7:

Paragraph 4:

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 x 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 x 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

Paragraph 5:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Why left shift of a negative signed value is not well-defined behavior?

Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • 6
    Nope. The question is here about the shifted value being negative, not the shift amount. – Lily Ballard Jun 23 '17 at 06:33
  • 4
    @alinsoar That is _not_ the same. It pertains to `x << n` where `n` is negative, NOT when `x` is negative. – cs95 Jun 23 '17 at 06:33
  • Consider removing the last paragraph. It attracts answers to only this simpler question, missing the more interesting one above. –  Jun 23 '17 at 06:42
  • 1
    @FelixPalmen the left-shift of a negative number is IMO more interesting, because it isn't detailed in the ANSI rationale. – Antti Haapala -- Слава Україні Jun 23 '17 at 06:44
  • @AnttiHaapala What I mean is *comparing* those two cases is most interesting in this question. –  Jun 23 '17 at 06:51
  • @AnttiHaapala: In cases where it would *obviously* make sense for most implementations to define a behavior, but where some implementations (e.g. a hypothetical C99 or C11 implementation using sign-magnitude integers), no rationale was given for leaving the behavior undefined since the Committee never imagined that compiler writers would treat UB as an invitation to behave nonsensically *even when a clear, obvious, unambiguous, and useful behavior was defined by the execution environment*. – supercat Oct 17 '17 at 22:30

0 Answers0