CERT.EXPR.PARENS

The operator’s precedence within expressions should be made explicit.

Vulnerability and risk

Mistakes regarding precedence rules can cause an expression to be evaluated in an unintended way, which can result in unexpected behavior.

Mitigation and prevention

Proper use of parentheses, defensively, reduces errors.

Vulnerable code example

Copy
   unsigned int test(unsigned int m, unsigned int n, unsigned int o)
   {
      unsigned int a;
      a = m == n | o ? o : n;
      o = m * n + a;
      return o;
   }

In this noncompliant example, Klocwork reports a CERT.EXPR.PARENS defect on lines 4 and 5 because the code does not use parentheses with operators to indicate precedence. This code can result in unexpected behavior.

Fixed code example

Copy
   unsigned int test(unsigned int m, unsigned int n, unsigned int o)
   {
      unsigned int a;
      a = (m == n) | o ? o : n;
      o = (m * n) + a;
      return o;
   }

The above example is compliant because it uses parentheses to properly indicate precedence.

Related checkers

  • MISRA.EXPR.PARENS.2012

External guidance