MISRA C++:2023 Rule 7.0.2
R2026b描述
There shall be no conversion to type bool. 1
理由
从基础类型转换为 bool 依赖于编译器将任何非零值视为 true。这与遵循 POSIX 标准并使用特定整数返回代码的 API 冲突。例如,返回值 -1 可能表示错误,但编译器会将此值隐式转换为 true。
此外,到 bool 的上下文转换的结果可能不符合开发人员的预期。因此,如果需要 bool 转换(例如 if 语句),请使用显式计算结果为 bool 类型的表达式。
Polyspace 实现
当您执行从基础类型到 bool 类型的上下文转换时,规则检查项会报告违规。
在以下情况下,转换为 bool 是合规的:
将大小为 1 的位字段的值转换为
bool,因为值0转换为false,而值1转换为true。对具有
explicit operator bool表达式的类类型使用static_cast<bool>。执行从指针或具有
explicit operator bool表达式的类到bool的上下文转换。使用其条件形式为
type-specifier-seq declarator的while循环。这是合规的,因为若要用类似方法实现与while循环相同的结果,需要对象具有不必要的作用域宽度。
故障排除
如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示。
示例
检查信息
| 组:标准转换 |
| 类别:必需 |
PQL 名称:std.misra_cpp_2023.R7_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:2025
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.