C Language Bit shifting using negative counts or beyond the width of the type


If the shift count value is a negative value then both left shift and right shift operations are undefined1:

int x = 5 << -3; /* undefined */
int x = 5 >> -3; /* undefined */

If left shift is performed on a negative value, it's undefined:

int x = -5 << 3; /* undefined */

If left shift is performed on a positive value and result of the mathematical value is not representable in the type, it's undefined1:

/* Assuming an int is 32-bits wide, the value '5 * 2^72' doesn't fit 
 * in an int. So, this is undefined. */
int x = 5 << 72;

Note that right shift on a negative value (.e.g -5 >> 3) is not undefined but implementation-defined.

1 Quoting ISO/IEC 9899:201x, section 6.5.7:

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.