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

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

    Yes I agree that do while loops can be rewritten to a while loop, however I disagree that always using a while loop is better. do while always get run at least once and that is a very useful property (most typical example being input checking (from keyboard))

    #include 
    
    int main() {
        char c;
    
        do {
            printf("enter a number");
            scanf("%c", &c);
    
        } while (c < '0' ||  c > '9'); 
    }
    

    This can of course be rewritten to a while loop, but this is usually viewed as a much more elegant solution.

提交回复
热议问题