AutosarC++17_03-A5.0.2

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

Required inputs: IR

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.

Exceptions

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 271927 2017-03-24 12:01:35Z piotr.tanski $
#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 [6]: 5-0-13 The condition of an if-statement and the condition of an iteration statement shall have type bool.

Possible Messages

Key

Text

Severity

Disabled

nonbool_if_condition

Condition must have type bool

None

False

nonbool_logical_operator_operand

Sub-condition must have type bool

None

False

nonbool_loop_condition

Condition must have type bool

None

False

Options

only_in_conditions

only_in_conditions : bool = True

If True, only logical operators inside conditions are checked.
 

only_pointer_types

only_pointer_types : bool = False

If true, only report if expressions of pointer type are used.
 

report_do_while_false

report_do_while_false : bool = True

Whether do ... while(0) should be reported.
 

report_while_true

report_while_true : bool = True

Whether while(1) ... should be reported.