views:

197

answers:

7

Why do some people use while(true){} blocks in their code? How does it work?

+2  A: 

while (the condition){do the function} when the condition is true.. it will do the function.

so while(true) the condition is always true it will continue looping.

the coding will never proceed.

william
The coding may proceed, but without exiting the loop (say using a `break;`) the processing will never continue outside the loop.
drachenstern
I mean.. it will continue looping there if he ne'er use any keyword to break the loop.
william
+7  A: 

It's just a loop that never ends on its own, known as an "infinite loop". (Often times, that's a bad thing.)

When it's empty, it serves to halt the program indefinitely*; otherwise there's typically some condition in the loop that, when true, breaks the loop:

while (true)
{
    // ...

    if (stopLoop)
        break;

    // ...
}

This is often cleaner than an auxiliary flag:

bool run = true;
while (run)
{
    // ...

    if (stopLoop)
    {
        run = false;
        continue; // jump to top
    }

    // ...
}

Also note some will recommend for (;;) instead, for various reasons. (Namely, it might get rid of a warning akin to "conditional expression is always true".)

*In most languages.

GMan
It's not a "halt" so much as a "spin rapidly in place".
Jeremy Friesner
@Jeremy: Fair. :) Unless I define "halt" as "executes no statements beyond the scope of the `while` loop", then I leave my post as is. :P
GMan
Thanks Gman ...
trusktr
+1  A: 

It's a loop that runs forever, unless there's a break statement somewhere inside the body.

Oli Charlesworth
+2  A: 

It's an infinite loop. At each iteration, the condition will be evaluated. Since the condition is true, which is always... true... the loop will run forever. Exiting the loop is done by checking something inside the loop, and then breaking if necessary.

By placing the break check inside the loop, instead of using it as the condition, this can make it more clear that you're expecting this to run until some event occurs.

A common scenario where this is used is in games; you want to keep processing the action and rendering frames until the game is quit.

Michael Madsen
oh, true, i guess so! thanks.
trusktr
+4  A: 

Rather than stuff all possible conditions in the while statement,

// Always tests all conditions in loop header:
while( (condition1 && condition2) || condition3 || conditionN_etc ) {

    // logic...

    if (notable_condition)
        continue;  // skip remainder, go direct to evaluation portion of loop

    // more logic
    // maybe more notable conditions use keyword: continue
}

Some programmers might argue it's better to put the conditions throughough the logic, (i.e. not just inside the loop header) and to employ break statements to get out at appropriate places. This approach will usually negate the otherwise original conditions to determine when to leave the loop (i.e. instead of when to keep looping).

// Always tests all conditions in body of loop logic: 
while(true) {

    //logic...

    if (!condition1 || !condition2)
        break;  // Break out for good. 

    // more logic...

    if (!condition3)
        break;

     // even more logic ...
}

In real life it's often a more gray mixture, a combination of all these things, instead of a polarized decision to go one way or another.

Usage will depend on the complexity of the logic and the preferences of the programmer .. and maybe on the accepted answer of this thread :)

Also don't forget about do..while. The ultimate solution may use that version of the while construct to twist conditional logic to their liking.

do {
    //logic with possible conditional tests and break or continue 
} while (true); /* or many conditional tests */

In summary it's just nice to have options as a programmer. So don't forget to thank your compiler authors.

John K
I prefer a `do { ... } while (false);` ;)
drachenstern
@drachenstern: Nice one.
John K
@John K ~ Lol, I thought so ;) ... Was waiting on someone to comment on my heater comment above :p ~~ Also, it'll be interesting to see who tries to argue on that one ... Would love to know who took more than one pass to figure out what that code does.
drachenstern
Believe it or not, Hitachi actually uses `do { ... } while (false);` loops in their hard drives.
Tyler
@drachenstern: A "do {...} while(0);" statement may have useful looping semantics, if one has both "break" and "continue" statements inside. The portion of the statement past the last break or continue will be executed only if no break or continue statements have executed. A "do {...} while(0);" statement, used with "breaks" but not "continue", may also be a useful alternative to if/elseif chains which require one or more statements between each "else" and the following "if".
supercat
@Tyler: I can believe it. I used such a construct in a flash file system, in the "find a free block" routine. I wonder if Hitachi use was similar?
supercat
haha do while false, so do nothing at all, ahha
trusktr
Very nice, thanks you
trusktr
@trusktr: `do`.. `while(false)` will run the loop logic once because the condition isn't evaluated until the bottom of the loop. Because it's false it will only ever run once; it's as if you didn't have the loop at all! Except that you can still use break or continue to get out of it at any point.
John K
do ... while(false) is the poor's man goto
belisarius
oooh ok, gotcha! Will "continue;" force the program to skip any remaining logic and evaluate the while condition?
trusktr
@truskr: yes, exactly. Good code sample on this page: http://msdn.microsoft.com/en-us/library/923ahwt1%28VS.80%29.aspx
John K
@supercat ~ Good point, I was ignoring the semantics of a break, but see the point. More concise than nested `if` s. Interesting trick, but not one I would ever use, except maybe in code golf.
drachenstern
@trusktr: A "continue" statement in a "while(x){...}" loop will re-evaluate the condition. A "continue" statement in a "for(x;y;z){...}" loop will perform the "z" operation and re-evaluate the condition. A "continue" statement in a "do{...}while(x);" loop will restart the loop without evaluating the condition.
supercat
@drachenstern: Suppose one is writing a routine to add some data to a block in flash memory, where it may or may not fit. If space can't be found on the current block, search for a block that has space. If none do, find a block with dead pages for reclamation. If none is available, find a purgeable block for reclamation. After doing any of those things, the code needs to restart the code that tried to fit a block in the page (though in the latter cases it will succeed). Not sure how to do the code nicely without using flags or redundant conditions, except via break/continue.
supercat
@supercat, by using lots of boolean flags of course! ... just depends on how expensive break becomes compared to nested if's. That's all. ~ But yeah, I made the comment in jest but I see the benefit to that style of coding. I just don't think I'll use it in my regular ASP.NET apps as the maintainability is just awkward. Now, were it on some micro with limited instructions, ram, etc, then sure, I'll go for all sorts of perverse optimizations.
drachenstern
+2  A: 

When Edsger W. Dijkstra was young, this was equivalent to:

         Do loop initialization
 label a:
         Do some code
         If (Loop is stoppable and End condition is met) goto label b
                     /* nowadays replaced by some kind of break() */
         Do some more code, probably incrementing counters
         go to label a
 label b:
         Be happy and continue

After Dijkstra decided to become Antigotoist, and convinced hordes of programmers to do so, a religious faith came upon earth and the truthiness of code was evident.

So the

 Do loop initialization
 While (true){
    some code
    If (Loop is stoppable and End condition is met) break();
    Do some more code, probably incrementing counters
 }
 Be happy and continue

Replaced the abomination.

Not happy with that, fanatics went above and beyond. Once proved that recursion was better, clearer and more general that looping, and that variables are just a diabolic incarnation, Functional Programming, as a dream, came true:

 Nest[f[.],x, forever[May God help you break]]   

And so, loops recursion became really unstoppable, or at least undemonstratively stoppable.

belisarius
+1  A: 

The real point to have while (true) {..} is when semantics of exit conditions have no strong single preference, so its nice way to say to reader, that "well, there are actually break conditions A, B, C .., but calculations of conditions are too lengthy, so they were put into inner blocks independently in order of expected probability of appearance".

RocketSurgeon