Why use infinite loops?

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

    One example is in a message pump type scenario, where you want to loop forever processing any messages that come in until told to stop. Another is if you want to take a periodic action then you might write an infinite loop with a sleep in it (though it may be better to use some form of timer for this).

    There may be some other places where the loop has to perform a certain amount of work to determine whether it should exit, and it may be cleaner just to use break when this condition is true rather than set some external flag to indicate the loop should exit.

    Generally though I think it's better practice to put your exit condition in the loop statement if possible, rather than to make it infinite and exit the loop using a break statement, because the exit condition of the loop is more obvious.

提交回复
热议问题