101 lines
2.3 KiB
Plaintext
101 lines
2.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The counter of a `for` loop should be updated in the loop's increment clause.
|
|
The purpose of a `for` loop is to iterate over a range using a counter variable.
|
|
It should not be used for other purposes, and alternative loops should be used in those cases.
|
|
|
|
If the counter is not updated, the loop will be infinite with a constant counter variable. If this is intentional, use a `while` or `do` `while` loop instead of a `for` loop.
|
|
|
|
If the counter variable is updated within the loop's body, try to move it to the increment clause.
|
|
If this is impossible due to certain conditions, replace the `for` loop with a `while` or `do` `while` loop.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
Move the counter variable update to the loop's increment clause.
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
for (int i = 0; i < 10; ) { // Noncompliant, i not updated in increment clause
|
|
// ...
|
|
i++;
|
|
}
|
|
----
|
|
|
|
[source,java,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
int sum = 0
|
|
for (int i = 0; i < 10; sum++) { // Noncompliant, i not updated in increment clause
|
|
// ...
|
|
i++;
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
for (i = 0; i < 10; i++) { // Compliant
|
|
// ...
|
|
}
|
|
----
|
|
|
|
[source,java,diff-id=2,diff-type=compliant]
|
|
----
|
|
int sum = 0
|
|
for (int i = 0; i < 10; i++) { // Compliant
|
|
// ...
|
|
sum++;
|
|
}
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
If this is impossible and the counter variable must be updated in the loop's body, use a `while` or `do` `while` loop instead.
|
|
|
|
[source,java,diff-id=3,diff-type=noncompliant]
|
|
----
|
|
for (int sum = 0; sum < 10) { // Noncompliant, sum not updated in increment clause
|
|
// ...
|
|
if (condition) sum++;
|
|
// ...
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=3,diff-type=compliant]
|
|
----
|
|
int sum = 0;
|
|
while (sum < 10) { // Compliant
|
|
// ...
|
|
if (condition) sum++;
|
|
// ...
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
include::../highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 21 Nov 2024, 16:48:00 Alban Auzeill wrote:
|
|
[test-code-support-investigation-for-java] Decision for scope: Main -> All.
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|