2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-10-16 16:34:38 +02:00
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.
2021-09-21 15:40:35 +02:00
2023-10-16 16:34:38 +02:00
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) { ... }
----
2021-09-21 15:40:35 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-09-21 15:40:35 +02:00
* 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
2024-01-15 17:15:56 +01:00
* CWE - https://cwe.mitre.org/data/definitions/783[CWE-783 - Operator Precedence Logic Error]
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]