What's the point of using "while (true) {...}"?
Asked Answered
S

8

6

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

Signac answered 16/10, 2010 at 0:23 Comment(3)
Because you want to have a task that run over and over again and there is no end condition, beside the end of the program.Muskogean
It's called an infinite loop. Also known as a heater.Heliport
I's Java (This parenthesis just adds enough characters to make StackOverflow accept the comment -- they have an idiotic rule that comments must be more than blah blah characters.)Signac
P
13

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.

Poree answered 16/10, 2010 at 0:27 Comment(0)
W
10

It's just a loop that never ends on its own, known as an . (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.

Webfooted answered 16/10, 2010 at 0:26 Comment(2)
It's not a "halt" so much as a "spin rapidly in place".Polyphemus
@Jeremy: Fair. :) Unless I define "halt" as "executes no statements beyond the scope of the while loop", then I leave my post as is. :PWebfooted
V
6

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.

Varicose answered 16/10, 2010 at 0:36 Comment(12)
I prefer a do { ... } while (false); ;)Heliport
@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.Heliport
Believe it or not, Hitachi actually uses do { ... } while (false); loops in their hard drives.Northumbria
@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".Hindemith
@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?Hindemith
@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.Varicose
oooh ok, gotcha! Will "continue;" force the program to skip any remaining logic and evaluate the while condition?Signac
@truskr: yes, exactly. Good code sample on this page: msdn.microsoft.com/en-us/library/923ahwt1%28VS.80%29.aspxVaricose
@Hindemith ~ 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.Heliport
@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.Hindemith
@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.Hindemith
@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.Heliport
O
4

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.

Offstage answered 16/10, 2010 at 0:42 Comment(0)
H
2

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.

Homochromous answered 16/10, 2010 at 0:25 Comment(2)
The coding may proceed, but without exiting the loop (say using a break;) the processing will never continue outside the loop.Heliport
I mean.. it will continue looping there if he ne'er use any keyword to break the loop.Homochromous
A
2

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

Antithesis answered 16/10, 2010 at 0:27 Comment(0)
S
1

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".

Spread answered 16/10, 2010 at 1:2 Comment(0)
P
1

This code refers to that inside of it will run indefinitely.

i = 0
while(true)
{
  i++;
}
echo i; //this code will never be reached

Unless inside of curly brackets is something like:

if (i > 100) {
  break; //this will break the while loop
}

or this is another possibility how to stop while loop:

if (i > 100) {
  return i;
}

It is useful to use during some testing. Or during casual coding. Or, like another answer is pointing out, in videogames.

But what I consider as bad practice is using it in production code.

For example, during debugging I want to know immediately what needs to be done in order to stop while. I don't want to search in the function for some hidden break or return.

Or the programmer can easily forget to add it there and data in a database can be affected before the code is stopped by other manners.

So ideal would be something like this:

i = 0
while(i < 100)
{
  i++;
}
echo i; //this code will be reached in this scenario
Pandean answered 10/2, 2023 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.