Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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
Include Page
CodeSonar_V
CodeSonar_V

LANG.ARITH.BIGSHIFT
LANG.ARITH.NEGSHIFT

Shift Amount Exceeds Bit Widthamount exceeds bit width
Negative Shift Amountshift amount

Compass/ROSE

 

 

Can detect violations of this rule. Unsigned operands are detected when checking for INT13-C. Use bitwise operators only on unsigned operands

ECLAIR
Include Page
ECLAIR_V
ECLAIR_V
CC2.INT34Partially implemented

Fortify SCA

5.0

 

Can detect violations of this rule with CERT C Rule Pack

LDRA tool suite

Include Page
LDRA_V
LDRA_V

403 S

Partially implemented

PRQA QA-C
Include Page
PRQA QA-C_v
PRQA QA-C_v

0499
2790
2791 (D)
2792 (A)
2793 (S)

Partially implemented

...

...