Is there ever a need for a “do {…} while ( )” loop?

后端 未结 19 2305
清歌不尽
清歌不尽 2020-11-29 02:44

Bjarne Stroustrup (C++ creator) once said that he avoids \"do/while\" loops, and prefers to write the code in terms of a \"while\" loop instead. [See quote below.]

S

19条回答
  •  情话喂你
    2020-11-29 03:22

    The following common idiom seems very straightforward to me:

    do {
        preliminary_work();
        value = get_value();
    } while (not_valid(value));
    

    The rewrite to avoid do seems to be:

    value = make_invalid_value();
    while (not_valid(value)) {
        preliminary_work();
        value = get_value();
    }
    

    That first line is used to make sure that the test always evaluates to true the first time. In other words, the test is always superfluous the first time. If this superfluous test wasn't there, one could also omit the initial assignment. This code gives the impression that it fights itself.

    In cases such like these, the do construct is a very useful option.

提交回复
热议问题