主要内容

MISRA C:2023 Rule 10.4

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

自 R2024a 起

描述

规则定义

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 类别:建议

版本历史记录

在 R2024a 中推出

全部展开


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.