Left shifting with a negative shift count

Negative integers on right-hand side is undefined behavior in the C language.

ISO 9899:2011 6.5.7 Bit-wise shift operators:

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.


As already answered by other members, it produces undefined behavior. What I would like to mention here is that you quote from the book ( "On one machine" ) seems to be partial. It does not generalize the behavior. The book might also have explained that the behavior is undefined as per the standard. BTW, I was just going through "The New C Standard - An Economic and Cultural Commentary" and found this statement :

The Intel Pentium SAL instruction (generated by both gcc and Microsoft C++ to evaluate left-shifts) only uses the bottom five bits of the shift amount

This very well explains why a left shift of -5 could result into a left shift of 27 ( for 2's complement representation of negative numbers )


The behaviour is undefined.

In 5-bit binary arithmetic, two's-complement -5 has the same binary representation as unsigned +27, which probably explains that particular platform.