From Surf Wiki (app.surf) — the open knowledge base
Infinite loop
Programming idiom
Programming idiom
the programming term
In computer programming, an infinite loop (or endless loop){{cite web |access-date=2020-01-22 |archive-date=2020-08-01 |archive-url=https://web.archive.org/web/20200801213748/https://www.yourdictionary.com/endless-loop |url-status=live |access-date=2020-01-22 |archive-date=2019-07-15 |archive-url=https://web.archive.org/web/20190715101446/https://whatis.techtarget.com/definition/infinite-loop-endless-loop |url-status=live
There is no general algorithm to determine whether a computer program contains an infinite loop or not; this is the halting problem.
Overview
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition,{{cite magazine |access-date=2020-01-23 |archive-date=2020-08-01 |archive-url=https://web.archive.org/web/20200801213624/http://www.flowjournal.org/tag/loop-media/?print=print-search |url-status=live |access-date=February 7, 2024 |archive-date=July 26, 2019 |archive-url=https://web.archive.org/web/20190726232111/https://www.pcmag.com/encyclopedia/term/48051/non-preemptive-multitasking |url-status=live
Intended vs unintended looping
Looping is repeating a set of instructions until a specific condition is met. An infinite loop occurs when the condition will never be met due to some inherent characteristic of the loop.
Intentional looping
There are a few situations when this is desired behavior. For example, the games on cartridge-based game consoles typically have no exit condition in their main loop, as there is no operating system for the program to exit to; the loop runs until the console is powered off.
Modern interactive computers require that the computer constantly be monitoring for user input or device activity, so at some fundamental level there is an infinite processing idle loop that must continue until the device is turned off or reset. In the Apollo Guidance Computer, for example, this outer loop was contained in the Exec program,{{cite web |access-date=2020-01-23 |archive-date=2016-11-05 |archive-url=https://web.archive.org/web/20161105060425/http://klabs.org/history/history_docs/mit_docs/1711.pdf |url-status=live
Multi-threading
In multi-threaded programs some threads can be executing inside infinite loops without causing the entire program to be stuck in an infinite loop. If the main thread exits, all threads of the process are forcefully stopped, thus all execution ends and the process/program terminates. The threads inside the infinite loops can perform "housekeeping" tasks or they can be in a blocked state waiting for input (from socket/queue) and resume execution every time input is received.
Unintentional looping
Most often, the term is used for those situations when this is not the intended result; that is, when this is a bug.{{cite web |access-date=January 22, 2020 |archive-date=August 2, 2020 |archive-url=https://web.archive.org/web/20200802040416/https://nyxcrossword.com/2013/10/1013-13-new-york-times-crossword.html |url-status=live
One common cause, for example, is that a programmer intends to iterate over sequence of nodes in a data structure such as a linked list or tree, executing the loop code once for each node. Improperly formed links can create a reference loop in the data structure, where one node links to another that occurs earlier in the sequence. This makes part of the data structure into a ring, causing naive code to loop forever.
While most infinite loops can be found by close inspection of the code, there is no general method to determine whether a given program will ever halt or will run forever; this is the undecidability of the halting problem.
Interruption
As long as the system is responsive, infinite loops can often be interrupted by sending a signal to the process (such as SIGINT in Unix), or an interrupt to the processor, causing the current process to be aborted. This can be done in a task manager, in a terminal with the Control-C command,{{cite web |access-date=January 22, 2020 |archive-date=July 24, 2020 |archive-url=https://web.archive.org/web/20200724200739/https://pen-testing.sans.org/resources/papers/gcih/buffer-overflow-exploit-dameware-remote-control-software-104168 |url-status=live
Language support
Infinite loops can be implemented using various control flow constructs. Most commonly, in unstructured programming this is jump back up (goto), while in structured programming this is an indefinite loop (while loop) set to never end, either by omitting the condition or explicitly setting it to true, as while (true) ....
Some languages have special constructs for infinite loops, typically by omitting the condition from an indefinite loop. Examples include Ada (loop ... end loop), Fortran (DO ... END DO), Go (for { ... }), Ruby (loop do ... end), and Rust (loop { ... }).
Infinite loops can also be created using recursion. This process is called infinite recursion.
Examples of intentional infinite loops
This is a loop that will print "Infinite loop" without halting, in C:
#include <stdio.h>
int main() {
for (;;) {
printf("Infinite loop\n");
}
return 0;
}
The form for (;;) for an infinite loop is traditional, appearing in the standard reference The C Programming Language, and is often pronounced "forever." However, its presence does not guarantee an infinite loop since the loop can be terminated by breaking using break, returning using return, or jumping using goto.
In C and C-derived languages, an infinite loop is perhaps more modernly expressed as while (true):
#include <stdio.h>
int main() {
while (true) {
printf("Infinite loop\n");
}
return 0;
}
In the descendant languages of C, such as C++, Java, and C#, it is more idiomatic to use while (true).
A similar example in 1980s-era BASIC:
10 PRINT "INFINITE LOOP"
20 GOTO 10
A similar example in MS-DOS compatible batch files:
:A
echo Infinite Loop
goto :A
The while loop never terminates because its condition is always true.
In Bourne Again Shell:
for ((;;)); do
echo "Infinite Loop"
done
Examples of unintentional infinite loops
Mathematical errors
Here is one example of an infinite loop in Visual Basic:
dim x as integer
do while x < 5
x = 1
x = x + 1
loop
This creates a situation where x will never be greater than 5, since at the start of the loop code, x is assigned the value of 1 (regardless of any previous value) before it is changed to x + 1. Thus the loop will always result in x = 2 and will never break. This could be fixed by moving the x = 1 instruction outside the loop so that its initial value is set only once.
In some languages, programmer confusion about mathematical symbols may lead to an unintentional infinite loop. For example, here is a snippet in C:
#include <stdio.h>
int main(void) {
int a = 0;
while (a < 10) {
printf("%d\n", a);
if (a = 5) {
printf("a equals 5!\n");
}
++a;
}
return 0;
}
The expected output is the numbers 0 through 9, with an interjected "a equals 5!" between 5 and 6. However, in the line "if (a = 5)" above, the = (assignment) operator was confused with the == (equality test) operator. Instead, this will assign the value of 5 to a at this point in the program. Thus, a will never be able to advance to 10, and this loop cannot terminate.
Rounding errors
| ... |
|---|
Unexpected behavior in evaluating the terminating condition can also cause this problem. Here is an example in C:
float x = 0.1;
while (x != 1.1) {
printf("x = %22.20f\n", x);
x += 0.1;
}
On some systems, this loop will execute ten times as expected, but on other systems it will never terminate. The problem is that the loop terminating condition (x != 1.1) tests for exact equality of two floating point values, and the way floating point values are represented in many computers will make this test fail, because they cannot represent the value 0.1 exactly, thus introducing rounding errors on each increment (cf. box).
The same can happen in Python:
x: float = 0.1
while x != 1:
print(x)
x += 0.1
Because of the likelihood of tests for equality or not-equality failing unexpectedly, it is safer to use greater-than or less-than tests when dealing with floating-point values. For example, instead of testing whether x equals 1.1, one might test whether `(x
A similar problem occurs frequently in numerical analysis: in order to compute a certain result, an iteration is intended to be carried out until the error is smaller than a chosen tolerance. However, because of rounding errors during the iteration, the specified tolerance can never be reached, resulting in an infinite loop.
Multi-party loops
An infinite loop may be caused by several entities interacting. Consider a server that always replies with an error message if it does not understand the request. Even if there is no possibility for an infinite loop within the server itself, a system comprising two of them (A and B) may loop endlessly: if A receives a message of unknown type from B, then A replies with an error message to B; if B does not understand the error message, it replies to A with its own error message; if A does not understand the error message from B, it sends yet another error message, and so on.
One common example of such situation is an email loop. An example of an email loop is if someone receives mail from a no reply inbox, but their auto-response is on. They will reply to the no reply inbox, triggering the "this is a no reply inbox" response. This will be sent to the user, who then sends an auto reply to the no-reply inbox, and so on and so forth.
Pseudo-infinite loops
A pseudo-infinite loop is a loop that appears infinite but is really just a very long loop.
Impossible termination condition
An example for loop in C:
for (unsigned int i = 1; i != 0; i++) {}
It appears that this will go on indefinitely, but in fact the value of i will eventually reach the maximum value storable in an unsigned int and adding 1 to that number will wrap-around causing an integer overflow, breaking the loop. The actual limit of i depends on the details of the system and compiler used. With arbitrary-precision arithmetic, this loop would continue until the computer's memory could no longer hold i. If i was a signed integer, rather than an unsigned integer, overflow would be undefined.
References
References
- (3 October 2018). "Halting Problem in Theory of Computation".
- [[b:Ada Programming/Control#Endless Loop. Ada Programming: Control: Endless Loop]]
- "Endless loop in C/C++".
This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.
Ask Mako anything about Infinite loop — get instant answers, deeper analysis, and related topics.
Research with MakoFree with your Surf account
Create a free account to save articles, ask Mako questions, and organize your research.
Sign up freeThis content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.
Report