Is while (true) with break bad programming practice?

后端 未结 22 2272
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:38

I often use this code pattern:

while(true) {

    //do something

    if() {
        break;
    }

}   

Another progr

22条回答
  •  春和景丽
    2020-11-27 05:00

    It depends on what you’re trying to do, but in general I prefer putting the conditional in the while.

    • It’s simpler, since you don't need another test in the code.
    • It’s easier to read, since you don’t have to go hunting for a break inside the loop.
    • You’re reinventing the wheel. The whole point of while is to do something as long as a test is true. Why subvert that by putting the break condition somewhere else?

    I’d use a while(true) loop if I was writing a daemon or other process that should run until it gets killed.

提交回复
热议问题