Main Content

MISRA C++:2008 Rule 5-0-13

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

Description

Rule Definition

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

Rationale

When you use a non-Boolean expression as a condition for if, while, and for statements, the expression is implicitly converted to bool. Such an implicit conversion might make developer intent unclear and hide errors that lead to bugs that are difficult to diagnose. For instance:

int flag;
//...
if(flag = 0){
//..
}
In the preceding code, it is not clear whether the condition flag = 0 is intended to be an assignment. The compiler casts the return value of the assignment operation into a bool, which is used as the condition for the if statement. If the developer intent is to test whether flag equals 0, then the missing = in the code results in bugs that are difficult to diagnose.

As an exception, conditions of the format type-specifier-seq declarator does not need to be Boolean. For instance:

while(int* p_int = foo())
In this case, the developer intent is clear because of the presence of the type specifier. Avoiding such assignments might make the code difficult to read.

Polyspace Implementation

Polyspace® flags the use of non-Boolean expressions as conditions in if, for, and while statements. As an exception, Polyspace does not flag a non-Boolean condition if the expression is a declaration.

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

typedef unsigned char         uint8_t;
typedef signed   int          int32_t;
typedef          bool         bool_t;

#include <cstddef>

namespace NS
{
extern int32_t* fn();
extern bool      fn2();
void foo(uint8_t u8)
{
    while (int32_t* p = fn()) {                   // Compliant by exception
        // Code
    }
    // Avoiding assignment altogather in condition statements
    // sometimes lead to clunky code
    do {
        int32_t* p = fn();
        if (NULL == p) {
            break;
        }
        // Code/*...*/
    } while (true);

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

    if (u8) {}                                       // Non-compliant

}
};

In this example, Polyspace flags the use of non-Boolean expressions as conditions.

As the do-while loop shows, avoiding declarations in condition statement might lead to code that is difficult to read. Non-Boolean conditions that are declarations are compliant with this rule as exceptions.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b