主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

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

描述

规则定义

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,则移位行为未定义。

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 类别:必需

版本历史记录

全部展开


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.