Rule A5-0-2 (required, implementation, automated)

The condition of an if-statement and the condition of an iteration statement shall have type bool.

Rationale

If an expression with type other than bool is used in the condition of an if-statement or iteration-statement, then its result will be implicitly converted to bool. The condition expression shall contain an explicit test (yielding a result of type bool) in order to clarify the intentions of the developer. Note that if a type defines an explicit conversion to type bool, then it is said to be “contextually converted to bool” (Section 4.0(4) of ISO/IEC 14882:2014 [3]) and can be used as a condition of an if-statement or iteration statement.

Exception

A condition of the form type-specifier-seq declarator is not required to have type bool. This exception is introduced because alternative mechanisms for achieving the same effect are cumbersome and error-prone.

Example

// $Id: A5-0-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
#include <memory>

extern std::int32_t* Fn();
extern std::int32_t Fn2();
extern bool Fn3();
void F() noexcept(false)
{
std::int32_t* ptr = nullptr;

while ((ptr = Fn()) != nullptr) // Compliant
{
// Code
}

// The following is a cumbersome but compliant example
do
{
std::int32_t* ptr = Fn();

if (nullptr == ptr)
{
break;
}

// Code
} while (true); // Compliant

std::unique_ptr<std::int32_t> uptr;
if (!uptr) // Compliant - std::unique_ptr defines an explicit conversion to
// type bool.
{
// Code
}

while (std::int32_t length = Fn2()) // Compliant by exception
{
// Code
}

while (bool flag = Fn3()) // Compliant
{
// Code
}

if (std::int32_t* ptr = Fn())

; // Compliant by exception

if (std::int32_t length = Fn2())
; // Compliant by exception

if (bool flag = Fn3())
; // Compliant

std::uint8_t u = 8;

if (u)

; // Non-compliant

bool boolean1 = false;
bool boolean2 = true;

if (u && (boolean1 <= boolean2))
; // Non-compliant

for (std::int32_t x = 10; x; --x)
; // Non-compliant

}

See also

MISRA C++ 2008 [7]: 5-0-13 The condition of an if-statement and the condition of an iteration statement shall have type bool.