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){ //.. }
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())
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
Check Information
Group: Expressions |
Category: Required |
Version History
Introduced in R2013b