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

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

    do-while is a loop with a post-condition. You need it in cases when the loop body is to be executed at least once. This is necessary for code which needs some action before the loop condition can be sensibly evaluated. With while loop you would have to call the initialization code from two sites, with do-while you can only call it from one site.

    Another example is when you already have a valid object when the first iteration is to be started, so you don't want to execute anything (loop condition evaluation included) before the first iteration starts. An example is with FindFirstFile/FindNextFile Win32 functions: you call FindFirstFile which either returns an error or a search handle to the first file, then you call FindNextFile until it returns an error.

    Pseudocode:

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

提交回复
热议问题