Why use infinite loops?

前端 未结 14 1962
轮回少年
轮回少年 2021-02-08 13:33

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:58

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

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

    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?

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

    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 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:05
    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().

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

    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)
提交回复
热议问题