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
I used to use them when waiting for multiple threads to complete in c#, but now I use the ThreadPool class.
I would consider using an infinite loop to program the guidance system of a missile.
while ( true ) { go2Target ( ) ; }
From the perspective of the missile's guidance computer, the loop once started does repeat until the end of time.
Perhaps a purists would favor
while ( ! blown2Bits ( ) ) { go2Target ( ) ; }
but then how do you implement the blow2Bits method? what would it mean if blow2Bits returned true?
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.
I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.
while( 1 )
{
game->update();
game->render();
}
Edit: That is, my app is fundamentally based around an infinite loop, and I can't be bothered to refactor everything just to have the aesthetic purity of always terminating by falling off the end of main().
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.