Log in / create account | Login with OpenID
DocForge
An Open Wiki For Software Developers

Infinite loop

From DocForge

An infinite loop is a segment of code which executes forever without external intervention. This might be done intentionally, such as in a video game runtime where the system must continue to act until the user quits. Infinite loops are a class of software bugs when done unintentionally.

Common Cases [edit]

The most obvious case of an infinite loop is a looping control flow statement with a condition which will never be false, causing the loop to naturally end. For any loop which might intentionally have a permanently true condition a break should be included. A loop might intentionally have an always-true condition, but this is typically bad practice to use unless necessary.

// An always-true condition
while (true) {
  echo "Running...\n";
}
 
// An always-true condition containing a break
$i = 0;
while (true) {
  echo "Running...\n";
  $i++;
  if ($i == 4) {
    break;
  }
}
 
// An always-true conditional loop, 
// containing a break which might never be executed
while (true) {
  echo "Running...\n";
  // Can we be certain the file will ever be that large?
  if (filesize("temp.txt") > 100) {
    break;
  }
}

Another possible cause of an infinite loop bug is a missed condition when using recursion.

function foo($iteration = 0) {
  echo "Running...\n";
  if ($iteration == 3) {
    exit();
  }
  $iteration += 2;
  foo($iteration);
}
foo();