Main Content

MISRA C:2023 Rule 12.2

The right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operand

Since R2024a

Description

Rule Definition

The right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operand.

Rationale

Consider this statement:

var = abc << num;
If abc is a 16-bit integer, then num must be in the range 0..15, (nonnegative and less than 16). If num is negative or greater than 16, then the shift behavior is undefined.

Polyspace Implementation

Polyspace® raises a violation when the right operand of a shift operator exceeds the range defined in this rule. When the right operand is a variable, the violation is raised unless all possible value of the operand remains within the range defined in this rule.

When a preprocessor directive performs a shift operation on a number literal, Polyspace assumes that the number is 64 bits wide. The valid shift range for such a number is between 0 and 63. For instance:

#if (1 << 64) //Noncompliant
//...
#endif
When bitfields are within a complex expression, Polyspace extends this check onto the bitfield field width or the width of the base type.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

void foo(void) {
  int i;
  unsigned int BitPack = 0U;
  
  for (i = 0; i < 32; i++) {
    BitPack |= (1U << ((unsigned int)i));  //Noncompliant
  }
}

In this example, the left operand 1U of the shift operator has an essential type unsigned char. Acceptable values for the right operand lies in the range from zero to seven. Because the right operand i ranges from zero to 31, Polyspace flags the shift operation.

Check Information

Group: Expressions
Category: Required
AGC Category: Required

Version History

Introduced in R2024a