MISRA C++:2023 Rule 7.0.2
Description
Rule Definition
There shall be no conversion to type
        bool. 1
      
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 - boolbecause a value of- 0is converted to- falseand a value of- 1is converted to- true.
- Using - static_cast<bool>for a class type with an- explicit operator boolexpression.
- Performing a contextual conversion to - boolfrom a pointer or a class with an- explicit operator boolexpression.
- Using a - whileloop that has a condition in the form- type-specifier-seq declarator. This is compliant because similar methods for achieving the same result as the- whileloop 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
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.