Is while (true) with break bad programming practice?

后端 未结 22 2315
-上瘾入骨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 04:50

    I prefer

    while(!) {
        //do something
    }
    

    but I think it's more a matter of readability, rather than the potential to "forget the break." I think that forgetting the break is a rather weak argument, as that would be a bug and you'd find and fix it right away.

    The argument I have against using a break to get out of an endless loop is that you're essentially using the break statement as a goto. I'm not religiously against using goto (if the language supports it, it's fair game), but I do try to replace it if there's a more readable alternative.

    In the case of many break points I would replace them with

    while( ! ||
           ! ||
           ! ) {
        //do something
    }
    

    Consolidating all of the stop conditions this way makes it a lot easier to see what's going to end this loop. break statements could be sprinkled around, and that's anything but readable.

提交回复
热议问题