主要内容

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

MISRA C:2012 Rule 10.4

Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category

描述

规则定义

Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category 1 .

理由

在类型之间使用隐式转换可能会导致意外结果,包括可能会丢失值、符号或精度。

有关基本类型的详细信息,请参阅Essential Types in MISRA C Rules 10.x

Polyspace 实现

如果一个运算的两个操作数具有不同的基本类型,检查项将触发该规则的违规。检查项消息说明运算两侧检测到的类型。

如果一个操作数是常量零,则检查项不会触发该规则的违规。

如果一个运算有一个无符号整数操作数和一个有符号整数常量操作数,并且有符号常量与无符号等效常量的二进制表示相同,则 Polyspace® 不报告违规。例如,在此代码中,Polyspace 假设表达式 (var + 1) 的类型本质上为无符号整数,因为 11U 具有相同的二进制表示形式:

unsigned int var;
int signed_var = (int) (var + 1);
此假设使上述代码合规。

故障排除

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

示例

全部展开

#define S64_MAX (9223372036854775807LL)
#define S64_MIN (-9223372036854775808LL)
long long input_s64_a, input_s64_b, result_s64;

void my_func(void){
   if (input_s64_a < S64_MIN + input_s64_b) { //Noncompliant: 2 violations
      result_s64 = S64_MIN;
   }
}

在此示例中,S64_MIN 的类型本质上为无符号类型。值 9223372036854775808LL 比 64 位变量所能表示的最大值多 1。因此,值溢出,结果循环到负值,因此 -9223372036854775808LL 本质上为无符号类型。

运算 input_s64_a < S64_MIN + input_s64_b 违反规则两次。

  • + 运算违反了规则。左操作数本质上为无符号类型,右操作数为有符号类型。

  • < 运算也违反了该规则。由于类型提升,+ 运算的结果本质上为无符号类型。现在,< 运算的左操作数本质上为有符号类型,而右操作数本质上为无符号类型。

检查信息

组:基本类型模型
类别:必需
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.