Why use infinite loops?

前端 未结 14 1952
深忆病人
深忆病人 2021-02-08 13:34

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

相关标签:
14条回答
  • 2021-02-08 13:50

    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.

    0 讨论(0)
  • 2021-02-08 13:53

    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.

    0 讨论(0)
  • 2021-02-08 13:53

    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.

    0 讨论(0)
  • 2021-02-08 13:55

    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.

    0 讨论(0)
  • 2021-02-08 14:01

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

    0 讨论(0)
  • 2021-02-08 14:01

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

    0 讨论(0)
提交回复
热议问题