MISRA C++:2008 Rule 5-0-14
The first operand of a conditional-operator shall have type bool
Description
Rule Definition
The first operand of a conditional-operator shall have type bool.
Rationale
When you use a non-Boolean expression as the first operand of the ?
operator, 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, val; //... flag= 1; val = (flag=0)?2:3;
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
?
operator. In this case, the developer intent might be to test the
value of flag
. You might expect val
to be 3, but it
becomes 2 because of the implicit conversion to bool
in the first
operand.Polyspace Implementation
Polyspace® raises a violation of this rule if a non-Boolean expression is used as the
first argument of the ?
operator.
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