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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With