主要内容

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

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 违反了规则。该表达式始终评估为真,因为 realReading 是两个 uint8_t 变量的乘积,因此不能超过 UINT32_MAX

  • 函数 mightExceedHardwareCapacity() 中的表达式 realReading < UINT8_MAX 没有违反规则,因为该表达式未计算为常量值。if 分支和 else 分支均可访问。

#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;
    }
}

检查信息

组:与语言无关的问题
类别:建议

版本历史记录

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