Why use infinite loops?

前端 未结 14 1961
轮回少年
轮回少年 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 14:06

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

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

    That's an incomplete example because it can be refactored to be an end-test loop with no loss of clarity, function or performance.

    int scoped_variable;
    do {
        scoped_variable = getSomeValue();
    } while (scoped_variable != some_value);
    

    Infinite loops are most often used when the loop instance doesn't have the termination test at the top or the bottom, in the simplest case. This tends to happen when there is two parts to the loop: code that must execute each time, and code that must only execute between each iteration. This tends to happen in languages like C when doing things like reading from a file or processing a database resultset where a lot has to be done explicitly. Most languages with newer paradigms can structure such code actually into the test.

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