Common Causes of Infinite Loops
- Infinite loops cause frustrating hangups in your program.the programmer and a computer image by Andrey Andreev from Fotolia.com
A computer programming loop executes an iterative process that runs a finite number of times (n). Set a variable i, known as the loop variant, and perform a test called a termination check. If the test evaluates to true, then the loop will terminate.
A simple example loop prints the numbers from 1 to 10. Create a loop variant i and set the value to 1. On each iteration of the loop, print the current value of i and increment i by 1. The termination check will end the loop if i is greater than 10 at the end of the loop body.
i = 1
loop
print i
i = i + 1
if i <= 10 then goto loop
However, a few common programming errors will result in infinite loops that can hang your program. - The termination check relies on the loop variant i getting closer to the termination condition. If the loop variant stays constant and doesn't change, then the termination check will always fail and the loop will continue indefinitely.
This problem will also occur if the loop variant depends on an unaccounted-for condition. Suppose your program prints every number between 1 and 5, then 7, then terminates. Your loop might look as follows:
i = 1
loop
print i
if i < 5 i = i + 1 (increments the loop variant, prints the numbers 1 through 5)
if i <= 7 goto loop (resets the loop for values of i less than or equal to 7)
In this loop, when i reaches 5, the loop will restart without ever incrementing and print 5 forever. The program must include a line that changes the loop variant.
i = 1
loop
print i
if i < 5 i = i + 1 (increments the loop variant, prints the numbers 1 through 5)
else i = i + 2 (increments by 2 when i reaches 5)
if i <= 7 goto loop (resets the loop when i reaches 7)
This loop will terminate after i reaches 7. - You may set a command in the middle of the loop body that resets the loop variant and creates an infinite loop. For example:
loop
i = 1 (resets the loop variant to 1)
print i
i = i + 1
if i < 5 goto loop
This sets i back to 1 at every iteration, yielding an infinite loop. - The loop variant must go toward the termination condition on each iteration.
i = 1
loop
print i
if i = 2 then i = i - 1
i = i + 1
if i < 3 goto loop
In this example the loop will hang when i reaches 2. You might make this kind of mistake when writing complicated loops like string parsing. - i = 1
loop
print i
i = i + 1
if i > 0 goto loop
In this example, the termination condition will cause an infinite loop as i increases without limit on every iteration.