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

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

    It's all about readability.
    More readable code leads to less headache in code maintenance, and better collaboration.
    Other considerations (such as optimization) are, by far, less important in most cases.
    I'll elaborate, since I got a comment here:
    If you have a code snippet A that uses do { ... } while(), and it's more readable than its while() {...} equivalent B, then I'd vote for A. If you prefer B, since you see the loop condition "up front", and you think it's more readable (and thus maintainable, etc.) - then go right ahead, use B.
    My point is: use the code that is more readable to your eyes (and to your colleagues'). The choice is subjective, of course.

提交回复
热议问题