Bitwise shifts include left-shift operations of the form shift-expression <<
additive-expression and right-shift operations of the form shift-expression >>
additive-expression. The integer promotions are performed on the operands, each of which has an integer type. 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. See also undefined behavior 51 of Annex J of C11 [ISO/IEC 9899:2011].
In almost every case, an attempt to shift by a negative number of bits or by more bits than exist in the operand indicates a bug (logic error). This is different from overflow, where there is simply a representational deficiency. (See INT32-C. Ensure that operations on signed integers do not result in overflow.)
...
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 and can be either an arithmetic (signed) shift:
...
CERT C++ Secure Coding Standard: INT34-CPP. Do not shift a negative number of bits or more bits than exist in the operand
ISO/IEC 9899:2011 Section Section 6.5.7, "Bitwise shift operators"
...