Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

C programmers commonly make errors regarding the precedence rules of C operators due to the unintuitive low-precedence levels of &, |, ^, <<, and >>. Mistakes regarding precedence rules can be avoided by the suitable use of parentheses. Using parentheses defensively reduces errors and, if not taken to excess, makes the code more readable.

Section 6.5 of the C standard [ISO/IEC 9899:19992011] (C99) defines the precedence of operation by the order of the subclauses.

...

Code Block
bgColor#FFCCCC
langc

x & 1 == 0

Because of operator precedence rules, the expression is parsed as

Code Block
bgColor#FFCCCC
langc

x & (1 == 0)

which evaluates to

Code Block
bgColor#FFCCCC
langc

(x & 0)

and then to 0.

Compliant Solution

...

Code Block
bgColor#ccccff
langc

(x & 1) == 0

Exceptions

EXP00-EX1: Mathematical expressions that follow algebraic order do not require parentheses. For instance, in the expression

Code Block

x + y * z

the multiplication is performed before the addition by mathematical convention. Consequently, parentheses to enforce this would enforce the algebraic order would be redundant.

Code Block
bgColor#ffcccc
langc

x + (y * z)

Risk Assessment

...

section

ECLAIR

exprprns

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V
section

361 S

section

Fully

Implemented

implemented

Section
Include Page
ECLAIR_V
ECLAIR_V
Section
Section

Fully

Implemented

implemented

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...

CERT C++ Secure Coding Standard: EXP00-CPP. Use parentheses for precedence of operation

ISO/IEC 9899:19992011 Section 6.5, "Expressions"

ISO/IEC TR 24772 "JCW Operator precedence/Order order of Evaluationevaluation"

MISRA Rule 12.1

Bibliography

...