Why is this an issue?
The rules of operator precedence are complicated and can lead to errors. For this reason, parentheses should be used for clarification in complex
statements. However, this does not mean that parentheses should be gratuitously added around every operation.
Parentheses are not needed:
- with a unary operator, except when
!
is used as left operand in comparison expressions
- when all the operators in an expression are the same
- when only a single operator is involved
- around the right-hand side of an assignment operator unless the right-hand side itself contains an assignment
Parentheses are needed:
- in the condition of a ternary operator if it uses operators
- when overloaded shift operator
<<
or >>
is used in an expression with comparison operators
Noncompliant code example
x = a + b;
x = a * -1;
x = a + b + c;
x = f ( a + b, c );
x = a == b ? a : a - b; // Noncompliant
x = a + b - c + d; // Noncompliant
x = a * 3 + c + d; // Noncompliant
if (a = f(b,c) == true) { ... } // Noncompliant; == evaluated first
x - b ? a : c; // Noncompliant; "-" evaluated first
s << 5 == 1; // Noncompliant; "<<" evaluated first
Compliant solution
x = a + b;
x = a * -1;
x = a + b + c;
x = f ( a + b, c );
x = ( a == b ) ? a : ( a - b );
x = ( a + b ) - ( c + d );
x = ( a * 3 ) + c + d;
if ( (a = f(b,c)) == true) { ... }
(x - b) ? a : c; // Compliant
(s << 5) == 1; // Compliant
Resources
- MISRA C:2004, 12.1 - Limited dependence should be placed on C’s operator precedence rules in expressions
- MISRA C:2004, 12.2 - The value of an expression shall be the same under any order of evaluation that the standard permits.
- MISRA C:2004, 12.5 - The operands of a logical && or || shall be primary-expressions.
- MISRA C++:2008, 5-0-1 - The value of an expression shall be the same under any order of evaluation that the standard permits.
- MISRA C++:2008, 5-0-2 - Limited dependence should be placed on C++ operator precedence rules in expressions
- MISRA C++:2008, 5-2-1 - Each operand of a logical && or || shall be a postfix-expression.
- MISRA C:2012, 12.1 - The precedence of operators within expressions should be made explicit
- CERT, EXP00-C. - Use parentheses for precedence of operation
- CERT, EXP53-J. - Use parentheses for precedence of operation
- MITRE, CWE-783 - Operator Precedence Logic Error