Main Content

MISRA C:2012 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

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 operand1 .

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 <= 8; i++) {
    BitPack |= (1U << ((unsigned int)i));  //Noncompliant
  }
}

In this example, the left operand of the shift operator << is the literal constant 1U. According to the essential type model, the essential type of this unsigned integer constant is the unsigned type of lowest rank (UTLR), which is unsigned char. Acceptable values for the right operand of this operator lies in the range from zero to seven. Because the right operand i ranges from zero to eight, Polyspace reports a violation.

Check Information

Group: Expressions
Category: Required
AGC Category: Required

Version History

expand all


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.