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

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

    In our coding conventions

    • if / while / ... conditions don't have side effects and
    • varibles must be initialized.

    So we have almost never a do {} while(xx) Because:

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

    is rewritten in:

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

    and

    Handle handle;
    Params params;
    if( ( handle = FindFirstFile( params ) ) != Error ) {
       do {
          process( params ); //process found file
       } while( ( handle = FindNextFile( params ) ) != Error ) );
    }
    

    is rewritten in:

    Params params(xxx);
    Handle handle = FindFirstFile( params );
    while( handle!=Error ) {
        process( params ); //process found file
        handle = FindNextFile( params );
    }
    

提交回复
热议问题