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 standard integer promotions are first 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 undefined behavior 51).)
Do not shift an expression by a negative number of bits or by a number greater than or equal to the precision of the promoted left operand. The precision of an integer type is the number of bits it uses to represent values, excluding any sign and padding bits. For unsigned integer types the width and the precision are the same, whereas for signed integer types the width is one greater than the precision. This rule uses precision instead of width because, in almost every case, an attempt to shift by a number of bits greater than or equal to the precision of the operand indicates a bug (logic error). A logic error is different from overflow, in which there is simply a representational deficiency. In general, shifts should only be performed on unsigned operands (see INT13-C. Use bitwise operators only on unsigned operands).
Noncompliant Code Example (Left Shift, Unsigned Type)
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| LANG.ARITH.BIGSHIFT | Shift Amount Exceeds Bit Widthamount exceeds bit width | ||||||
|
| Can detect violations of this rule. Unsigned operands are detected when checking for INT13-C. Use bitwise operators only on unsigned operands | |||||||
ECLAIR |
| CC2.INT34 | Partially implemented | ||||||
5.0 |
| Can detect violations of this rule with CERT C Rule Pack | |||||||
| 403 S | Partially implemented | |||||||
PRQA QA-C |
| 0499 | Partially implemented |
...
...