MISRA C:2012 Rule 12.1
The precedence of operators within expressions should be made explicit
Description
Rule Definition
The precedence of operators within expressions should be made explicit.
Rationale
The C language has a large number of operators and their precedence is not intuitive. Inexperienced programmers can easily make mistakes. Remove any ambiguity by using parentheses to explicitly define operator precedence.
The following table list the MISRA C™ definition of operator precedence for this rule.
Description | Operator and Operand | Precedence |
---|---|---|
Primary | identifier, constant, string literal, (expression) | 16 |
Postfix | [] () (function call) . ->
++ (post-increment) -- (post-decrement) ()
{} (C99: compound literals) | 15 |
Unary |
| 14 |
Cast | () | 13 |
Multiplicative | * / % | 12 |
Additive | + - | 11 |
Bitwise shift | << >> | 10 |
Relational | <> <= >= | 9 |
Equality | == != | 8 |
Bitwise AND | & | 7 |
Bitwise XOR | ^ | 6 |
Bitwise OR | | | 5 |
Logical AND | && | 4 |
Logical OR | || | 3 |
Conditional | ?: | 2 |
Assignment | = *= /= += -= <<= >>= &= ^= |= | 1 |
Comma | , | 0 |
The precedence of an expression is the precedence of the 'root' element of the parse tree of the expression. In other words, the precedence of an expression is the precedence of the operation that is performed last in the expression. For example, consider this expression:
a - b << c + d
<<
, which has a precedence of 10. The operands
a - b
and c + d
have a rank 11. Using the precedence of an expression and its subexpression, the MISRA C:2012 standard recommends:
Enclose the operands of
sizeof
operator in parenthesis.Enclose an operand of an expression in parenthesis if all these conditions are true:
The operand has a precedence less than 13.
The operand has a greater precedence than the expression.
The precedence of the expression itself if between 2 to 12.
Polyspace Implementation
The rule checker reports a violation if any of these conditions are true:
The operands of an expression has a higher precedence than the root operator of the expression but the operands are not parenthesized.
The operands of
sizeof
operator do not use parenthesis.
Violations of this rule is not reported for assignment operators, unary operators, subscripting operators, and comma operators.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Expressions |
Category: Advisory |
AGC Category: Advisory |