views:

1784

answers:

14

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?

+9  A: 

I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.

AShelly
+5  A: 

Finite state machines. They're not supposed to end until you reach an end state, at which point you break or return.

Ignacio Vazquez-Abrams
I don't understand this one. Why not just write something like, "while (!machine.state == finished) {machine.nextState();}
Moishe
It wouldn't necessarily be as clear, especially if you wanted to test the `machine.state` variable at a particular point in the loop.
Head Geek
+21  A: 

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.

Tony Meyer
FWIW, I also prefer "while(true)" or "while(1)" to "for (;;)". Easier to read, IMO.
Tony Meyer
Great example of a construct that would otherwise require duplication: A; while(something else) { B; A; }
Marcus Griep
A: 

I used to use them when waiting for multiple threads to complete in c#, but now I use the ThreadPool class.

Fry
+1  A: 

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.

Greg Beech
+6  A: 
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().

Menkboy
So, how do you exit?
James Curran
I do a load of cleanp and then call 'exit()'. I needed this clean shutdown function anyway (for eg. assert()), and why have two different exit paths?
Menkboy
+2  A: 

That's an incomplete example because it can be refactored to be an end-test loop with no loss of clarity, function or performance.

int scoped_variable;
do {
    scoped_variable = getSomeValue();
} while (scoped_variable != some_value);

Infinite loops are most often used when the loop instance doesn't have the termination test at the top or the bottom, in the simplest case. This tends to happen when there is two parts to the loop: code that must execute each time, and code that must only execute between each iteration. This tends to happen in languages like C when doing things like reading from a file or processing a database resultset where a lot has to be done explicitly. Most languages with newer paradigms can structure such code actually into the test.

staticsan
Are you sure that variable is still in scope outside the block?
Moishe
And why not: for (int scoped_variable; (scoped_variable = getSomeValue()) != some_value; ) ; (empty loop body). That works as both a C99 and a C++ program using GCC/G++ 4.3.1 on Solaris.
Jonathan Leffler
Edited the code fragment to fix a scoping issue. That for(...) loop is also legitimate, but is a somewhat unusual use of for(...) and a lot of programmers would shy away from that for that reason.
staticsan
A: 

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.

Loren Pechtel
+1  A: 

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.

Draemon
+1  A: 

I use them to write Linux daemons / services that loop until kill / other termination signals are received.

Chris Kloberdanz
A: 

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.

orj
+2  A: 

Nearly all apps use an infinite Main loop. ;)

Gary Willoughby
A: 

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.

Time Machine
A: 

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?

emory