Possibly unintended evaluation of expression because of operator precedence rules
Operator precedence rules cause unexpected evaluation order in arithmetic expression
Description
This defect occurs when an arithmetic expression result is possibly unintended because operator precedence rules dictate an evaluation order that you do not expect.
The defect highlights expressions of the form x
. Here,
op_1
y
op_2
zop_1
and op_2
are operator
combinations that commonly induce this error. For instance, x == y |
z
.
The checker does not flag all operator combinations. For instance, x == y ||
z
is not flagged because you most likely intended to perform a logical OR
between x == y
and z
. Specifically, the checker
flags these combinations:
&&
and||
: For instance,x || y && z
orx && y || z
.Assignment and bitwise operations: For instance,
x = y | z
.Assignment and comparison operations: For instance,
x = y != z
orx = y > z
.Comparison operations: For instance,
x > y > z
(except when one of the comparisons is an equalityx == y > z
).Shift and numerical operation: For instance,
x << y + 2
.Pointer dereference and arithmetic: For instance,
*p++
.
Risk
The defect can cause the following issues:
If you or another code reviewer reviews the code, the intended order of evaluation is not immediately clear.
It is possible that the result of the evaluation does not meet your expectations. For instance:
In the operation
*p++
, it is possible that you expect the dereferenced value to be incremented. However, the pointerp
is incremented before the dereference.In the operation
(x == y | z)
, it is possible that you expectx
to be compared withy | z
. However, the==
operation happens before the|
operation.
Fix
See if the order of evaluation is what you intend. If not, apply parentheses to implement the evaluation order that you want.
For better readability of your code, it is good practice to apply parenthesis to implement an evaluation order even when operator precedence rules impose that order.
Examples
Result Information
Group: Programming |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax: OPERATOR_PRECEDENCE |
Impact: High |
Version History
Introduced in R2015b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)