Why use infinite loops?

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

    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.

提交回复
热议问题