Why use infinite loops?

前端 未结 14 1965
深忆病人
深忆病人 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 14:06

    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.

提交回复
热议问题