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.
Finite state machines. They're not supposed to end until you reach an end state, at which point you break or return.
One example is in a message pump type scenario, where you want to loop forever processing any messages that come in until told to stop. Another is if you want to take a periodic action then you might write an infinite loop with a sleep in it (though it may be better to use some form of timer for this).
There may be some other places where the loop has to perform a certain amount of work to determine whether it should exit, and it may be cleaner just to use break
when this condition is true rather than set some external flag to indicate the loop should exit.
Generally though I think it's better practice to put your exit condition in the loop statement if possible, rather than to make it infinite and exit the loop using a break
statement, because the exit condition of the loop is more obvious.
Infinite loops are useful mostly in daemon/service processes or the main loop in a game. You can even get cute with them, eg:
const bool heatDeathOfTheUniverse = false;
do
{
// stuff
} while(!heatDeathOfTheUniverse);
They should not be used to "wait" for things like threads as was suggested by Fry. You can use the Join method of a thread object for that.
However, if you're in a situation where your tech lead says, "infinite loops are verboten & so are multiple method/function returns & breaks" you can also do stuff like this:
bool done = false;
while(!done)
{
if(done = AreWeDone()) continue; // continue jumps back to start of the loop
}
Of course if you tech lead is forcing you to do such things you should start looking for a new job.
For more details on the continue keyword see this MSDN article.
Nearly all apps use an infinite Main loop. ;)