主要内容

MISRA C:2012 Rule 12.2

R2026b

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

描述

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

理由

请参考以下语句:

var = abc << num;
如果变量 abc 为本质整数类型,且整数大小为 16 位,则 num 必须在 0-15 范围内(即非负且小于 16)。如果 num 为负或大于 16,则移位行为是未定义的。

有关用于确定本质类型的规则的详细信息,请参阅 Essential Type Model Used in MISRA C Rule Checking。

Polyspace 实现

当移位运算符的右操作数超出本规则定义的范围时,Polyspace® 会引发违规。当右操作数是变量时,除非该操作数的所有可能值均保持在本规则定义的范围内,否则会引发违规。

当预处理器指令对数字字面量执行移位运算时,Polyspace 假定该数字为 64 位宽。此类数字的有效移位范围为 0 到 63。例如:

#if (1 << 64) //Noncompliant
//...
#endif
当位字段位于复杂表达式中时,Polyspace 会将此检查扩展到这些位字段的字段宽度或基类型的宽度。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示。

示例

全部展开

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

在上方示例中,移位运算符 << 的左操作数是字面值常量 1U。根据基本类型模型,此无符号整数常量的基本类型是最低秩无符号类型 (UTLR),即 unsigned char。该运算符的右操作数的可接受值范围是 0 到 7。由于右操作数 i 的范围是 0 到 8,因此 Polyspace 会报告违规。

检查信息

组:表达式
类别:必需
AGC 类别:必需
PQL 名称:std.misra_c_2012.R12_2

版本历史记录

全部展开


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:2025

  • MISRA C++:2008

  • MISRA C++:2023

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