主要内容

MISRA C++:2023 Rule 7.0.1

R2026b

There shall be no conversion from type bool

自 R2024b 起

描述

There shall be no conversion from type bool. 1

理由

当布尔值隐式转换为其他类型时,可能会发生逻辑错误。这些转换后的值可能被用于非预期上下文中,从而导致难以诊断的细微 Bug。此外,此规则还有助于识别本应使用逻辑运算符(例如 || 或 &&)却意外使用了按位运算符(例如 | 或 &)的情况,因为使用按位运算符而非逻辑运算符可能会导致从 bool 类型转换为其他类型。

Polyspace 实现

当您执行从 bool 类型到其他类型的转换(包括整型提升或算术转换)时,规则检查项会报告违规。一种例外情况是将布尔值赋给长度为 1 的位字段。在这种情况下,false 值转换为 0,而 true 值转换为 1。

故障排除

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

示例

全部展开

int example1()
{
    bool flagA = true;
    bool flagB = false;

    if (flagA & flagB)      //Noncompliant
    {
        //do something
    }

    if (flagA && flagB)     //Compliant
    {
        //do something
    }

    switch (flagB)          //Noncompliant
    {
    case 0:
        //do something
        break;
    case 1:
        //do something
        break;
    default:
        break;
    }
}

在此示例中:

  • if (flagA & flagB) 不合规,因为其中使用了按位运算符 &。使用 & 会导致 flagA 和 flagB 转换为整数。请改用逻辑运算符 &&。

  • switch (flagB) 不合规。将 flagB 用作 switch 表达式会导致 flagB 转换为整数。在这种情况下,可以将 switch 语句替换为等效的 if 语句。

检查信息

组:标准转换
类别:必需
PQL 名称:std.misra_cpp_2023.R7_0_1

版本历史记录

在 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:2025

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.