74 lines
1.4 KiB
Plaintext
74 lines
1.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
An infinite loop will never end while the program runs, meaning you have to kill the program to get out of the loop.
|
|
Every loop should have an end condition, whether by meeting the loop's termination condition or via a `break` statement.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
for (;;) { // Noncompliant; end condition omitted
|
|
// ...
|
|
}
|
|
----
|
|
|
|
[source,java,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
int j;
|
|
while (true) { // Noncompliant; end condition omitted
|
|
j++;
|
|
}
|
|
----
|
|
|
|
[source,java,diff-id=3,diff-type=noncompliant]
|
|
----
|
|
int k;
|
|
boolean b = true;
|
|
while (b) { // Noncompliant; b never written to in loop
|
|
k++;
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java,diff-id=2,diff-type=compliant]
|
|
----
|
|
int j;
|
|
while (true) { // reachable end condition added
|
|
j++;
|
|
if (j == Integer.MIN_VALUE) { // true at Integer.MAX_VALUE +1
|
|
break;
|
|
}
|
|
}
|
|
----
|
|
|
|
[source,java,diff-id=3,diff-type=compliant]
|
|
----
|
|
int k;
|
|
boolean b = true;
|
|
while (b) {
|
|
k++;
|
|
b = k < Integer.MAX_VALUE;
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Standards
|
|
* https://wiki.sei.cmu.edu/confluence/x/lzZGBQ[CERT, MSC01-J.] - Do not use an empty infinite loop
|
|
|
|
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[]
|