72 lines
2.1 KiB
Plaintext
72 lines
2.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The rules of operator precedence are complicated and can lead to errors. For this reason, parentheses should be used for clarification in complex statements. However, this does not mean that parentheses should be gratuitously added around every operation.
|
|
|
|
|
|
This rule raises issues when ``++&&++`` and ``++||++`` are used in combination, when assignment and equality or relational operators are used together in a condition, and for other operator combinations according to the following table:
|
|
|
|
[frame=all]
|
|
[cols="^1,^1,^1,^1,^1,^1"]
|
|
|===
|
|
||``+``, ``++-++``, ``++*++``, ``++/++``, ``++%++``|``++<<++``, ``++>>++``, ``++>>>++``|``++&++``|``++^++``| ``++\|++``
|
|
|
|
|``+``, ``++-++``, ``++*++``, ``++/++``, ``++%++``| |x|x|x|x
|
|
|``++<<++``, ``++>>++``, ``++>>>++``|x| |x|x|x
|
|
|``++&++``|x|x| |x|x
|
|
|``++^++``|x|x|x| |x
|
|
| ``++\|++`` |x|x|x|x|
|
|
|===
|
|
|
|
This rule also raises an issue when the "true" or "false" expression of a ternary operator is not trivial and not wrapped inside parentheses.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
x = a + b - c;
|
|
x = a + 1 << b; // Noncompliant
|
|
y = a == b ? a * 2 : a + b; // Noncompliant
|
|
|
|
if ( a > b || c < d || a == d) {...}
|
|
if ( a > b && c < d || a == b) {...} // Noncompliant
|
|
if (a = f(b,c) == 1) { ... } // Noncompliant; == evaluated first
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
x = a + b - c;
|
|
x = (a + 1) << b;
|
|
y = a == b ? (a * 2) : (a + b);
|
|
|
|
if ( a > b || c < d || a == d) {...}
|
|
if ( (a > b && c < d) || a == b) {...}
|
|
if ( (a = f(b,c)) == 1) { ... }
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/YdYxBQ[CERT, EXP00-C.] - Use parentheses for precedence of operation
|
|
* https://wiki.sei.cmu.edu/confluence/x/ZzZGBQ[CERT, EXP53-J.] - Use parentheses for precedence of operation
|
|
* CWE - https://cwe.mitre.org/data/definitions/783[CWE-783 - Operator Precedence Logic Error]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|