The other day, a programmer I follow on Twitter was pleased because he had found a good use for a do/while loop.
The rule of thumb is that you should use always use a do/while loop when the body of the loop must execute at least once. Use a while loop when the body of the loop may never execute.
Maybe it’s true that a while loop is indicated more often than a do/while loop, but I’ve often seen programmers do a little jury-rigging to patch up the while loop to do their bidding when a do/while would have meant less typing and have made more sense.
Why? Well, programmers get into habits. If you get to know while very well, you may be shy about using do/while.
I think repeat/until is superior to do/while for these reasons:
- do/while‘s ending condition is the same as while‘s starting condition. Pascal’s until condition is logically negated, which I think is more natural at the end of a loop. Do something over and over UNTIL something is true, rather than do something over and over WHILE something is true. REPEAT UNTIL i hits 5, rather than DO WHILE i is less than 5. A possible solution would be to allow do/until as well as do/while. This would allow for backward compatibility. Someone remind me I said that the next time I invent my own computer language.
In short, the do/while construct just doesn’t sit quite right in C, encouraging the overuse of the while loop, which sits just fine. In any case, repeat/until seems to get more use in Pascal than do/while gets in C.
Don’t forget do/while is there, waiting for you to be excited to use it. It’s the right choice when you must execute the body at least once.