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
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).