Take the 2-minute tour ×

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)
    } 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?

share|improve this question

closed as not constructive by Ferruccio, A.H., the Tin Man, Corbin, Mr.Wizard Oct 5 '12 at 23:00


I had a CS professor circa 1997 proclaim that your two choices in programming were C or Pascal, and that you should choose Pascal because it didn't let you increment loop counters from inside the loop. He might have been right, but boy was he wrong. –  MusiGenesis Oct 22 '08 at 2:23
Wow, this is a perfect example of why inexact duplicates should not be merged. Looks like half the answers must originally have been given to a totally different question along the lines of "what is the difference". I almost downvoted some of them before I realised it is not the answerers who deserve to lose reputation, but the overzealous moderator who took perfectly good answers and moved them to an unrelated question that they do not address. –  Porculus Jan 12 '11 at 0:16
What construct is "statistically more likely to be correct" is a bizarre criterion. What matters is, "What's correct for this particular problem?" Statistically, we want to add more often than we want to multiply. Would you therefore say that any time you need to do arithmetic, you should always use "+" and never use "*" because, "statistically", it's more often correct to add? Or, I go to the grocery store more often that I go to the car dealer, therefore, any time I leave the house I'll automatically go to the grocery store -- even if what I want to do is buy a new car. –  Jay Oct 18 '11 at 14:57
show 7 more comments

31 Answers

Generally, it depends on how you structure your code. And as someone already answered, some algorithms need at least one iteration performed. So, to escape additional iteration-count or at-least-one-interation-occured flag - you employ do/while.

share|improve this answer
add comment
