Is while (true) with break bad programming practice?

后端 未结 22 2280
-上瘾入骨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:42

    What your friend recommend is different from what you did. Your own code is more akin to

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

    which always run the loop at least once, regardless of the condition.

    But there are times breaks are perfectly okay, as mentioned by others. In response to your friend's worry of "forget the break", I often write in the following form:

    while(true){
        // do something
    if() break;
        // continue do something
    }
    

    By good indentation, the break point is clear to first time reader of the code, look as structural as codes which break at the beginning or bottom of a loop.

提交回复
热议问题