MISRA C++:2023 Rule 7.0.2
Description
Rule Definition
There shall be no conversion to type
bool
.
Rationale
Converting from a fundamental type to bool
relies on the compiler
treating any nonzero value as true
. This clashes with APIs that conform
to the POSIX standard and use specific integer return codes. For instance, a return value of
-1
could indicate an error, but the compiler implicitly converts this
value to true
.
Additionally, the outcome of a contextual conversion to bool
might
not match the developer expectations. Therefore, in situations requiring a
bool
conversion, such as an if
-statement, use an
expression that evaluates explicitly to a bool
type.
Polyspace Implementation
The rule checker reports a violation when you perform a contextual conversion from a
fundamental type to the bool
type.
Conversions to bool
are compliant in the following situations:
Converting a value with a bit-field of size 1 to
bool
because a value of0
is converted tofalse
and a value of1
is converted totrue
.Using
static_cast<bool>
for a class type with anexplicit operator bool
expression.Performing a contextual conversion to
bool
from a pointer or a class with anexplicit operator bool
expression.Using a
while
loop that has a condition in the formtype-specifier-seq declarator
. This is compliant because similar methods for achieving the same result as thewhile
loop require objects that are unnecessarily wide in scope.
Troubleshooting
If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Standard Conversions |
Category: Required |
Version History
Introduced in R2024b