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

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

    This is cleanest alternative to do-while that I have seen. It is the idiom recommended for Python which does not have a do-while loop.

    One caveat is that you can not have a continue in the since it would jump the break condition, but none of the examples that show the benefits of the do-while need a continue before the condition.

    while (true) {
           
           if (!condition) break;
           
    }
    

    Here it is applied to some of the best examples of the do-while loops above.

    while (true);  {
        printf("enter a number");
        scanf("%c", &c);
        if (!(c < '0' ||  c > '9')) break;
    } 
    

    This next example is a case where the structure is more readable than a do-while since the condition is kept near the top as //get data is usually short yet the //process data portion may be lengthy.

    while (true);  {
        // get data 
        if (data == null) break;
        // process data
        // process it some more
        // have a lot of cases etc.
        // wow, we're almost done.
        // oops, just one more thing.
    } 
    

提交回复
热议问题