This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 7.0.1 - There shall be no conversion from type bool
[conv.prom]
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
This rule applies to all implicit and explicit conversions, except for:
- The operands of an equality operator where both operands have type
bool; or
- An explicit cast from
bool to class T, when that class has a converting constructor with a parameter of type
bool:
-
T { true }
-
T ( true )
-
static_cast< T >( true )
-
( T )true — note that this violates M23_089: MISRA C++ 2023 Rule 8.2.2
Rationale
Values of type bool may be subject to integral promotion and the usual arithmetic conversions. However, occurrences are generally
indicative of an error or code obfuscation. For example, the use of bool operands with the bitwise operators is unlikely to be
intentional and is likely to indicate that a bitwise operator (&, |, ~) has been confused with a logical
operator (&&, ||, !). This rule allows errors such as this to be detected.
The integral promotion that occurs when an equality operator is used to compare two values of type bool is permitted as it is
benign.
Casting a bool to an integral type is not allowed as it is clearer to specify the values to which true and
false will be converted.
Exception
As there is no risk of confusion, a value of type bool may be assigned to a bit-field of length 1 — this is a common idiom
used when accessing hardware registers.
Example
bool b1 = true;
bool b2 = false;
double d1;
int8_t s8a;
if ( b1 & b2 ) // Non-compliant - b1 and b2 converted to int
if ( b1 < b2 ) // Non-compliant - b1 and b2 converted to int
if ( ~b1 ) // Non-compliant - b1 converted to int
if ( b1 ^ b2 ) // Non-compliant - b1 and b2 converted to int
if ( b1 == 0 ) // Non-compliant - b1 converted to int
double result = d1 * b1; // Non-compliant - b1 converted to double
s8a = static_cast< int8_t >( b1 ); // Non-compliant - b1 converted to int8_t
if ( b1 == false ) // Compliant - Boolean operands to equality
if ( b1 == b2 ) // Compliant - Boolean operands to equality
if ( b1 != b2 ) // Compliant - Boolean operands to equality
if ( b1 && b2 ) // Compliant - no conversion from bool
if ( !b1 ) // Compliant - no conversion from bool
s8a = b1 ? 3 : 7; // Compliant - no conversion from bool
void f( int32_t n );
bool b;
f( b ); // Non-compliant - b converted to int32_t
f( b ? 1 : 0 ); // Compliant - no conversion from bool
switch ( b ) // Non-compliant - b converted to int
struct A
{
explicit A( bool );
};
A anA { true }; // Compliant - constructor
anA = A { false }; // Compliant - explicit cast calls constructor
Copyright The MISRA Consortium Limited © 2023