Main Content

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 op_1 y op_2 z. Here, op_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 or x && y || z.

  • Assignment and bitwise operations: For instance, x = y | z.

  • Assignment and comparison operations: For instance, x = y != z or x = y > z.

  • Comparison operations: For instance, x > y > z (except when one of the comparisons is an equality x == 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 pointer p is incremented before the dereference.

    • In the operation (x == y | z), it is possible that you expect x to be compared with y | 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

expand all

int test(int a, int b, int c) {
    return(a & b == c);
}

In this example, the == operation happens first, followed by the & operation. If you intended the reverse order of operations, the result is not what you expect.

Correction — Parenthesis For Intended Order

One possible correction is to apply parenthesis to implement the intended evaluation order.

int test(int a, int b, int c) {
    return((a & b) == c);
}

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