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

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

    First of all, I do agree that do-while is less readable than while.

    But I'm amazed that after so many answers, nobody has considered why do-while even exists in the language. The reason is efficiency.

    Lets say we have a do-while loop with N condition checks, where the outcome of the condition depends on the loop body. Then if we replace it with a while loop, we get N+1 condition checks instead, where the extra check is pointless. That's no big deal if the loop condition only contains a check of an integer value, but lets say that we have

    something_t* x = NULL;
    
    while( very_slowly_check_if_something_is_done(x) )
    {
      set_something(x);
    }
    

    Then the function call in first lap of the loop is redundant: we already know that x isn't set to anything yet. So why execute some pointless overhead code?

    I often use do-while for this very purpose when coding realtime embedded systems, where the code inside the condition is relatively slow (checking the response from some slow hardware peripheral).

    0 讨论(0)
提交回复
热议问题