Main Content

MISRA C++:2023 Rule 7.0.2

There shall be no conversion to type bool

Since R2024b

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 of 0 is converted to false and a value of 1 is converted to true.

  • Using static_cast<bool> for a class type with an explicit operator bool expression.

  • Performing a contextual conversion to bool from a pointer or a class with an explicit operator bool expression.

  • Using a while loop that has a condition in the form type-specifier-seq declarator. This is compliant because similar methods for achieving the same result as the while 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

expand all

int exampleA(){
	class BoolConvertible {
	public:
		explicit operator bool() const { return true; } 
	};

	BoolConvertible obj;
	if (obj) {                        //Compliant
		//...
	}

	struct MyClass {
		int data;
	};
	
	
	int MyClass::*mptr = nullptr;
	if (mptr) {                        //Noncompliant
		//...
	}

	enum Color { RED, GREEN, BLUE };
	Color color = GREEN;
	if (color) {                       //Noncompliant
		//...
	}

	double value = 0.0;
	while (value) {                    //Noncompliant
		//...
	}

	int num = 42;
	if (num) {                         //Noncompliant
		//...
	}
}

In this example:

  • The class BoolConvertible contains an explicit operator bool expression making the conversion of obj to type bool compliant.

  • Variables mptr, color, value, and num are all contextually converted to type bool in noncompliant situations.

Check Information

Group: Standard Conversions
Category: Required

Version History

Introduced in R2024b