When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.
As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:
if (condition)
{
do
{
...
} while (same condition);
}
or the inverse (if
inside the while
), it makes me wonder if they actually wrote it that way or if they added the if
statement when they realized the loop didn't handle the null case.
I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?
First one may not execute at all if condition is false. Other one will execute at least once, then check the conidition.
It's more helpful to think in terms of common usage. The vast majority of while loops work quite naturally with
while
, even if they could be made to work withdo...while
, so basically you should use it when the difference doesn't matter. I would thus usedo...while
for the rare scenarios where it provides a noticeable improvement in readability.This isn't really an answer but a reiteration of something one of my lecturers said and it interested me at the time.
The two types of loop while..do and do..while are actually instances of a third more generic loop, which has the test somewhere in the middle.
Code block A is executed at least once and B is executed zero or more times, but isn't run on the very last (failing) iteration. a while loop is when code block a is empty and a do..while is when code block b is empty. But if you're writing a compiler, you might be interested in generalizing both cases to a loop like this.
The difference is obvious and allows you to have code run and then evaluate the result to see if you have to "Do it again" and the other method of while allows you to have a block of script ignored if the conditional is not met.
Yaa..its true.. do while will run atleast one time. Thats the only difference. Nothing else to debate on this
The use cases are different for the two. This isn't a "best practices" question.
If you want a loop to execute based on the condition exclusively than use for or while
If you want to do something once regardless of the the condition and then continue doing it based the condition evaluation. do..while