Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use infinite loops?

Another poster asked about preferred syntax for infinite loops.

A follow-up question: Why do you use infinite loops in your code? I typically see a construct like this:

for (;;) {
  int scoped_variable = getSomeValue();
  if (scoped_variable == some_value) {
    break;
  }
}

Which lets you get around not being able to see the value of scoped_variable in the for or while clause. What are some other uses for "infinite" loops?

like image 219
Moishe Lettvin Avatar asked Oct 22 '08 01:10

Moishe Lettvin


People also ask

Why would you use an infinite loop?

Usually, an infinite loop results from a programming error - for example, where the conditions for exit are incorrectly written. Intentional uses for infinite loops include programs that are supposed to run continuously, such as product demo s or in programming for embedded system s.

Why do we use infinite loop in microcontroller?

Infinite loops are required to ensure that your embedded systems keeps running and performs the desired operations when an event occurs and an action has to be performed by the system.

What is an infinite loop and why it is happen?

An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.

What happens if you run an infinite loop?

An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer. To avoid such incidents it is important to be aware of infinite loops so that we can avoid them.


1 Answers

A loop like:

while (true)
{
    // do something
    if (something else) break;
    // do more
}

lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).

If you've got a complex condition, you might also want to use this style to make the code clearer.

like image 111
Tony Meyer Avatar answered Oct 03 '22 12:10

Tony Meyer