主要内容

MISRA C++:2023 Rule 0.0.2

Controlling expressions should not be invariant

自 R2024b 起

描述

Controlling expressions should not be invariant. 1

理由

如果 ifforwhile 语句的控制表达式具有不变值,例如,计算结果始终为 true 或 false,则该表达式是死代码,可以删除而不会产生任何功能影响。编译器有时可以检测到这些不变表达式,并将其从最终可执行文件中删除。这些不变表达式通常表明存在编程错误,并可能导致代码意外地无法执行。

Polyspace 实现

如果 ifforwhile 等语句的控制表达式计算结果为常量值,则规则检查项会报告违规。

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

在此示例中:

  • mightExceedStorageCapacity() 函数中的表达式 realReading < UINT32_MAX 违反了规则。该表达式的计算结果始终为 true,因为 realReading 是两个 uint8_t 变量的乘积,因此不能超过 UINT32_MAX

  • mightExceedHardwareCapacity() 函数中的表达式 realReading < UINT8_MAX没有违反规则,因为该表达式的计算结果不是常量值。ifelse 分支均可达。

#include <climits>
#include <cstdint>

bool mightExceedStorageCapacity(uint8_t meterReading, uint8_t scale)
{
    uint32_t realReading = meterReading * scale;
    if (realReading < UINT32_MAX) { //Noncompliant
        return true;
    }
    else {
        return false;
    }
}

bool mightExceedHardWareCapacity(uint8_t meterReading, uint8_t scale)
{
    uint32_t realReading = meterReading * scale;
    if (realReading < UINT8_MAX) { //Compliant
        return true;
    }
    else {
        return false;
    }
}

检查信息

组:与语言无关的问题
类别:建议
PQL 名称:std.misra_cpp_2023.R0_0_2

版本历史记录

在 R2024b 中推出


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.