HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs ("pull the plug"). It may be intentional.


Overview

This differs from: * "a type of computer program that runs the same instructions continuously until it is either stopped or interrupted." Consider the following
pseudocode In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
: how_many = 0 while is_there_more_data() do how_many = how_many + 1 end display "the number of items counted = " how_many ''The same instructions'' were run ''continuously until it was stopped or interrupted'' . . . by the ''FALSE'' returned at some point by the function ''is_there_more_data''. By contrast, the following loop will not end by itself: birds = 1 fish = 2 while birds + fish > 1 do birds = 3 - birds fish = 3 - fish end ''birds'' will alternate being 1 or 2, while ''fish'' will alternate being 2 or 1. The loop will not stop unless an external intervention occurs ("pull the plug").


Details

An ''infinite loop'' is a sequence of instructions in a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to Execution (computing), execute. Computer programs are one component of software, which also includes software documentation, documentation and oth ...
which loops endlessly, either due to the
loop Loop or LOOP may refer to: Brands and enterprises * Loop (mobile), a Bulgarian virtual network operator and co-founder of Loop Live * Loop, clothing, a company founded by Carlos Vasquez in the 1990s and worn by Digable Planets * Loop Mobile, an ...
having no terminating condition, having one that can never be met, or one that causes the loop to start over. In older
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common daemon (computing), services for computer programs. Time-sharing operating systems scheduler (computing), schedule tasks for ef ...
s with
cooperative multitasking Cooperative multitasking, also known as non-preemptive multitasking, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, in order to run multiple ...
, infinite loops normally caused the entire system to become unresponsive. With the now-prevalent preemptive multitasking model, infinite loops usually cause the program to consume all available processor time, but can usually be terminated by the user.
Busy wait In computer science and software engineering, busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available. Spinning can also be u ...
loops are also sometimes called "infinite loops". Infinite loops are one possible cause for a computer "
freezing Freezing is a phase transition where a liquid turns into a solid when its temperature is lowered below its freezing point. In accordance with the internationally established definition, freezing means the solidification phase change of a liquid ...
"; others include thrashing,
deadlock In concurrent computing, deadlock is any situation in which no member of some group of entities can proceed because each waits for another member, including itself, to take action, such as sending a message or, more commonly, releasing a loc ...
, and
access violation Access may refer to: Companies and organizations * ACCESS (Australia), an Australian youth network * Access (credit card), a former credit card in the United Kingdom * Access Co., a Japanese software company * Access Healthcare, an Indian BPO se ...
s.


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 The Apollo Guidance Computer (AGC) was a digital computer produced for the Apollo program that was installed on board each Apollo command module (CM) and Apollo Lunar Module (LM). The AGC provided computation and electronic interfaces for guidanc ...
, for example, this outer loop was contained in the Exec program, and if the computer had absolutely no other work to do it would loop run a dummy job that would simply turn off the "computer activity" indicator light. Modern computers also typically do not halt the processor or motherboard circuit-driving clocks when they crash. Instead they fall back to an error condition displaying messages to the operator, and enter an infinite loop waiting for the user to either respond to a prompt to continue, or to reset the device.


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. Such errors are most common among novice programmers, but can be made by experienced programmers as well, because their causes can be quite subtle. One common cause, for example, is that the programmer intends to iterate over sequence of nodes in a
data structure In computer science, a data structure is a data organization, management, and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, ...
such as a
linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which ...
or
tree In botany, a tree is a perennial plant with an elongated stem, or trunk, usually supporting branches and leaves. In some usages, the definition of a tree may be narrower, including only woody plants with secondary growth, plants that are ...
, 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 In computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running, or continue to run forever. Alan Turing proved in 1936 that a ...
.


Interruption

As long as the system is responsive, infinite loops can often be interrupted by sending a signal to the process (such as
SIGINT Signals intelligence (SIGINT) is intelligence-gathering by interception of '' signals'', whether communications between people (communications intelligence—abbreviated to COMINT) or from electronic signals not directly used in communication ...
in Unix), or an
interrupt In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted, ...
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 Control+C is a common computer command. It is generated by pressing the key while holding down the key on most computer keyboards. In graphical user interface environments that use the control key to control the active program, control+C is o ...
command, or by using the
kill Kill often refers to: *Homicide, one human killing another *cause death, to kill a living organism, to cause its death Kill may also refer to: Media *'' Kill!'', a 1968 film directed by Kihachi Okamoto * ''Kill'' (Cannibal Corpse album), 2006 * ...
command or
system call In computing, a system call (commonly abbreviated to syscall) is the programmatic way in which a computer program requests a service from the operating system on which it is executed. This may include hardware-related services (for example, acc ...
. However, this does not always work, as the process may not be responding to signals or the processor may be in an uninterruptible state, such as in the Cyrix coma bug (caused by overlapping uninterruptible instructions in an
instruction pipeline In computer engineering, instruction pipelining or ILP is a technique for implementing instruction-level parallelism within a single processor. Pipelining attempts to keep every part of the processor busy with some instruction by dividing inco ...
). In some cases other signals such as
SIGKILL Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-co ...
can work, as they do not require the process to be responsive, while in other cases the loop cannot be terminated short of system shutdown.


Language support

Infinite loops can be implemented using various
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
constructs. Most commonly, in unstructured programming this is jump back up (
goto GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function c ...
), 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 ).


Examples of intentional infinite loops

A simple example (in C): #include int main() The form for (;;) for an infinite loop is traditional, appearing in the standard reference ''
The C Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as ...
'', and is often punningly pronounced "forever". This is a loop that will print "Infinite Loop" without halting. A similar example in 1980s-era
BASIC BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
: 10 PRINT "INFINITE LOOP" 20 GOTO 10 A similar example in
DOS DOS is shorthand for the MS-DOS and IBM PC DOS family of operating systems. DOS may also refer to: Computing * Data over signalling (DoS), multiplexing data onto a signalling channel * Denial-of-service attack (DoS), an attack on a communicat ...
batch files: :A echo Infinite Loop goto :A Here the loop is quite obvious, as the last line unconditionally sends execution back to the first. An example in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
while (true) An example in Bourne Again Shell for ((;;)); do echo "Infinite Loop" done An example in
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO( ...
loop


Examples of unintentional infinite loops


Mathematical errors

Here is one example of an infinite loop in
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to: * Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET * 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 given the value of 1, thus, the loop will always end in 2 and the loop will never break. This could be fixed by moving the x = 1 instruction outside the loop. Essentially what this infinite loop does is to instruct a computer to keep on adding 1 to 1 until 5 is reached. Since 1+1 always equals 2, this will never happen. In some languages, programmer confusion about the mathematical symbols may lead to an unintentional infinite loop. For example, here is a snippet in C: #include int main(void) 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 programmer has confused the = (assignment) operator 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) 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 In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can ...
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 = 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 <= 1.0), or (x < 1.1), either of which would be certain to exit after a finite number of iterations. Another way to fix this particular example would be to use an
integer An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
as a loop index, counting the number of iterations that have been performed. A similar problem occurs frequently in
numerical analysis Numerical analysis is the study of algorithms that use numerical approximation (as opposed to symbolic manipulations) for the problems of mathematical analysis (as distinguished from discrete mathematics). It is the study of numerical methods ...
: 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 email loop is an infinite loop phenomenon, resulting from mail servers, scripts, or email clients that generate automatic replies or responses. If one such automatic response triggers another automatic response on the other side, an email loop i ...
. 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.


Very large numbers

An example in
bash Bash or BASH may refer to: Arts and entertainment * ''Bash!'' (Rockapella album), 1992 * ''Bash!'' (Dave Bailey album), 1961 * '' Bash: Latter-Day Plays'', a dramatic triptych * ''BASH!'' (role-playing game), a 2005 superhero game * "Bash" ('' ...
: for x in $(seq 1000000000); do #loop code done


Impossible termination condition

An example
for loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two par ...
in C: unsigned int i; for (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 to 0, breaking the loop. The actual limit of i depends on the details of the system and
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
used. With
arbitrary-precision arithmetic In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are li ...
, this loop would continue until the computer's
memory Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remember ...
could no longer hold i. If i was a signed integer, rather than an unsigned integer, overflow would be undefined. In this case, the compiler could optimize the code into an infinite loop.


Infinite recursion

Infinite recursion is a special case of an infinite loop that is caused by
recursion Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematic ...
. The following example in VBA returns a stack overflow error: Sub Test1() Call Test1 End Sub


Break statement

A "while (true)" loop looks infinite at first glance, but there may be a way to escape the loop through a break statement or return statement. Example in PHP: while (true)


Alderson loop

''Alderson loop'' is a rare slang or
jargon Jargon is the specialized terminology associated with a particular field or area of activity. Jargon is normally employed in a particular communicative context and may not be well understood outside that context. The context is usually a partic ...
term for an infinite loop where there is an exit condition available, but inaccessible in the current implementation of the code, typically due to a programmer's error. These are most common and visible while
debugging In computer programming and software development, debugging is the process of finding and resolving '' bugs'' (defects or problems that prevent correct operation) within computer programs, software, or systems. Debugging tactics can involve i ...
user interface In the industrial design field of human–computer interaction, a user interface (UI) is the space where interactions between humans and machines occur. The goal of this interaction is to allow effective operation and control of the machine f ...
code. A C-like pseudocode example of an Alderson loop, where the program is supposed to sum numbers given by the user until zero is given, but where the programmer has used the wrong operator: int sum = 0; int i; while (true) The term allegedly received its name from a programmer (last name Alderson) who in 1996 had coded a modal
dialog box The dialog box (also called dialogue box (non-U.S. English), message box or simply dialog) is a graphical control element in the form of a small window that communicates information to the user and prompts them for a response. Dialog boxes ar ...
in
Microsoft Access Microsoft Access is a database management system (DBMS) from Microsoft that combines the relational Access Database Engine (ACE) with a graphical user interface and software-development tools (not to be confused with the old Microsoft Access ...
without either an OK or Cancel button, thereby disabling the entire program whenever the box came up.


See also

*
Cycle detection In computer science, cycle detection or cycle finding is the algorithmic problem of finding a cycle in a sequence of iterated function values. For any function that maps a finite set to itself, and any initial value in , the sequence of iter ...
*
Deadlock In concurrent computing, deadlock is any situation in which no member of some group of entities can proceed because each waits for another member, including itself, to take action, such as sending a message or, more commonly, releasing a loc ...
* Divergence (computer science) *
Fork bomb In computing, a fork bomb (also called rabbit virus or wabbit) is a denial-of-service attack In computing, a denial-of-service attack (DoS attack) is a cyber-attack in which the perpetrator seeks to make a machine or network resource unav ...
(an infinite loop is one of two key components) *
Goto GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function c ...
*
Infinite regress An infinite regress is an infinite series of entities governed by a recursive principle that determines how each entity in the series depends on or is produced by its predecessor. In the epistemic regress, for example, a belief is justified bec ...
*
Recursion (computer science) In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem. Recursion solves such recursive problems by using functions that call themselves ...


References


External links


Make an infinite loop
in several languages, o
programming-idioms.org
{{DEFAULTSORT:Infinite Loop Iteration in programming Recursion Software bugs