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

后端 未结 19 2335
清歌不尽
清歌不尽 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:02

    A do-while loop can always be rewritten as a while loop.

    Whether to use only while loops, or while, do-while, and for-loops (or any combination thereof) depends largely on your taste for aesthetics and the conventions of the project you are working on.

    Personally, I prefer while-loops because it simplifies reasoning about loop invariants IMHO.

    As to whether there are situations where you do need do-while loops: Instead of

    do
    {
      loopBody();
    } while (condition());
    

    you can always

    loopBody();
    while(condition())
    {
      loopBody();
    }
    

    so, no, you never need to use do-while if you cannot for some reason. (Of course this example violates DRY, but it's only a proof-of-concept. In my experience there is usually a way of transforming a do-while loop to a while loop and not to violate DRY in any concrete use case.)

    "When in Rome, do as the Romans."

    BTW: The quote you are looking for is maybe this one ([1], last paragraph of section 6.3.3):

    From my experience, the do-statement is a source of error and confusion. The reason is that its body is always executed once before the condition is tested. For the correct functioning of the body, however, a similar condition to the final condition has to hold in the first run. More often than I expected I have found these conditions not to be true. This was the case both when I wrote the program in question from scratch and then tested it as well as after a change of the code. Additionally, I prefer the condition "up-front, where I can see it". I therefore tend to avoid do-statements.

    (Note: This is my translation of the German edition. If you happen to own the English edition, feel free to edit the quote to match his original wording. Unfortunately, Addison-Wesley hates Google.)

    [1] B. Stroustrup: The C++ programming language. 3rd Edition. Addison-Wessley, Reading, 1997.

提交回复
热议问题