Bit shifting using negative counts or beyond the width of the type
suggest changeIf the shift count is negative, or is greater than or equal to the width of the promoted left operand, both left and right shifts are undefined1:
int negative_count = 5 << -3; /* undefined */
int also_negative = 5 >> -3; /* undefined */
int too_wide = 5 << 72; /* undefined when int is no wider than 72 bits */
A left shift of a negative value is undefined:
int negative_value = -5 << 3; /* undefined */
A left shift of a nonnegative value is also undefined when the mathematical result is not representable in the result type. This is a separate rule from an out-of-range shift count:
/* Assuming a 32-bit int, 1 << 31 is not representable in signed int. */
int too_large = 1 << 31; /* undefined */
A right shift of a negative value (for example, -5 >> 3) is not undefined, but it is 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents