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.
In almost every case, an attempt to shift by too much or by a negative amount a negative number of bits or by more bits than exist in the operand indicates a bug (logic error). This is different than overflow, where there is simply a representational deficiency (see INT32-C. Ensure that integer operations do not result in an overflow).
...
This compliant solution tests the suspect shift operation operations to guarantee there is no possibility of unsigned overflowundefined behavior.
Code Block | ||
---|---|---|
| ||
int si1, si2, sresult; unsigned int ui1, ui2, result; if ( (si2 < 0) || (si2 >= sizeof(int)*CHAR_BIT) ) { /* handle error condition */ } else { sresult = si1 >> si2; } if (ui2 >= sizeof(unsigned int)*CHAR_BIT) { /* handle error condition */ } else { uresult = ui1 >> ui2; } |
...