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 | ||||
---|---|---|---|---|
| ||||
x & 1 == 0
|
Because of operator precedence rules, the expression is parsed as
Code Block | ||||
---|---|---|---|---|
| ||||
x & (1 == 0)
|
which evaluates to
Code Block | ||||
---|---|---|---|---|
| ||||
(x & 0)
|
and then to 0
.
Compliant Solution
...
Code Block | ||||
---|---|---|---|---|
| ||||
(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 | ||||
---|---|---|---|---|
| ||||
x + (y * z)
|
Risk Assessment
...
Tool | Version | Checker | Description | section|||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
| 361 S section | Fully Implementedimplemented | ||||||||||
Section | |
| Section | exprprns Section | | Fully Implementedimplemented |
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
...