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
There are other questions relating to if/when it's ok to use break
in a loop. Let's assume that we agree that it's sometimes ok. In those circumstances (hopefully rare) I would use an infinite loop if there are a number of terminating conditions and no identifiable "primary" terminating condition.
It avoids a long series of disjunctions (or's) and also draws the reader's attention to the fact that there may (almost certainly will) be breaks in the loop.
Ultimately it's a matter of taste.
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.
Webservers use an infinite while loop:
while(true)
{
//Do something like respond to requests
}
They don't have to end unless you close your webserver application.
Other than embedded systems situations infinite loops always really are:
Repeat
Something
Until Exit_Condition;
But sometimes Exit_Condition isn't something that can actually be evaluated at the end of the loop. You could always set a flag, use that flag to skip the rest of the loop and then test it at the end but that means you are testing it at least twice (the code is slightly slower) and personally I find it less clear.
There are times when trading clarity for speed makes sense but something that gives neither clarity nor speed just to be technically correct? Sounds like a bad idea to me. Any competent programmer knows that while (true) means the termination condition is somewhere inside the loop.
I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.
I use them to write Linux daemons / services that loop until kill / other termination signals are received.