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

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

    Well maybe this goes back a few steps, but in the case of

    do
    {
         output("enter a number");
         int x = getInput();
    
         //do stuff with input
    }while(x != 0);
    

    It would be possible, though not necessarily readable to use

    int x;
    while(x = getInput())
    {
        //do stuff with input
    }
    

    Now if you wanted to use a number other than 0 to quit the loop

    while((x = getInput()) != 4)
    {
        //do stuff with input
    }
    

    But again, there is a loss in readability, not to mention it's considered bad practice to utilize an assignment statement inside a conditional, I just wanted to point out that there are more compact ways of doing it than assigning a "reserved" value to indicate to the loop that it is the initial run through.

提交回复
热议问题