
In some cases, the `rule.adoc` at root of a rule is never included anywhere and thus is dead code. It's a maintenance cost by itself, but also it misses opportunities to inline code that seems used by two documents when in fact only one document is actually rendered. And this missed opportunity, in turn, stops us from applying the correct language tag on the code samples.
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
|
|
* https://cwe.mitre.org/data/definitions/783[MITRE, 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[]
|