Why use infinite loops?

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

提交回复
热议问题