I've been programming for a while now (2 years work + 4.5 years degree + 1 year pre-college) and I've never used a do-while loop short of being forced to in the Introduction to Programming course. I have a growing feeling that I'm doing programming wrong if I never run into something so fundamental.

Could it be that I just haven't run into the correct circumstances?

What are some examples where it would be necessary to use a do-while instead of a while?

(My schooling was almost all in C/C++ and my work is in C#, so if there is another language where it absolutely makes sense because do-whiles work differently, then these questions don't really apply)

Edit: To clarify...I know the difference between a while and a do-while. While checks exit condition then performs tasks, do-while performs tasks then checks exit condition.

24 Answers
24

If you always want the loop to execute at least once. It's not common, but I do use it from time to time. One case where you might want to use it is trying to access a resource that could require a retry, e.g.

So I guess this would follow under the "I haven't run into that circumstance."
–
mphairJul 27 '10 at 19:11

3

honestly, i very rarely run into a circumstance when I just need to use a do..while..
–
Stan R.Jul 27 '10 at 19:12

Maybe a little short, but Bob is correct. Do/while should be used when you want to run the code block at least one time. You should use a while loop when you don't know if you even want to run it a single time. That said, I can tell you that with around 15 years of development experience, I've used many times more while loops than do/while loops.
–
ConsultUtahJul 27 '10 at 19:14

2

It is fairly common. But I don't see why in your example you would not use a while loop. And I don't see why this answer is being upvoted.
–
anonJul 27 '10 at 19:20

do-while is better if the compiler isn't competent at optimization. do-while has only a single conditional jump, as opposed to for and while which have a conditional jump and an unconditional jump. For CPUs which are pipelined and don't do branch prediction, this can make a big difference in the performance of a tight loop.

Also, since most compilers are smart enough to perform this optimization, all loops found in decompiled code will usually be do-while (if the decompiler even bothers to reconstruct loops from backward local gotos at all).

+1 I wonder if this is considered premature optimization
–
Josh StodolaJul 27 '10 at 19:38

1

Not only premature but useless. If you really wanted a while loop i.e. the ability to iterate 0 times, you have to enclose the loop in an if which brings that jump back in.
–
JeremyPJul 28 '10 at 16:10

1

@Jeremy: The jump you speak of is outside the loop, it isn't executed N times.
–
Ben VoigtJul 28 '10 at 23:58

Consider also the classic use of do-while in Duff's device (wherein a while loop is transformed into an unrolled do-while with a larger step plus a jump table to handle the remainder) which dramatically reduces the loop overhead -- in applications such as memset, memcmp, memcpy it may increase throughput by a factor of 10.
–
Ben VoigtJul 29 '10 at 4:35

Do while is useful for when you want to execute something at least once. As for a good example for using do while vs. while, lets say you want to make the following: A calculator.

You could approach this by using a loop and checking after each calculation if the person wants to exit the program. Now you can probably assume that once the program is opened the person wants to do this at least once so you could do the following:

Actually, now that you mention it, any kind of console based menu driven interface would do well in a do...while loop as well. For example, prompting for options (one key at a time) and only exiting when they choose continue or quit.
–
JoshuaJul 27 '10 at 19:23

Why/how is this better than a standard while?
–
Josh StodolaJul 27 '10 at 19:33

1

@SLC But wouldn't you want to check if the directory exists before-hand anyways?
–
Josh StodolaJul 27 '10 at 19:40

1

@Josh In this example, yes. But if you were trying to open a connection to a busy server, you'd connect first, and see if the response was 'busy'. If it was, you'd try again a few times before giving up.
–
SLCJul 27 '10 at 20:02

In theory they are useful when you want the loop body to execute once before the exit condition check. The problem is that for the few instances where I don't want the check first, typically I want the exit check in the middle of the loop body rather than at the very end. In that case, I prefer to use the well-known for (;;) with an if (condition) exit; somewhere in the body.

In fact, if I'm a bit shaky on the loop exit condition, sometimes I find it useful to start writing the loop as a for (;;) {} with an exit statement where needed, and then when I'm done I can see if it can be "cleaned up" by moving initilizations, exit conditions, and/or increment code inside the for's parentheses.

Out of curiosity...why "for(;;)" instead of "while(true)"?
–
mphairJul 27 '10 at 19:20

3

Probably just taste. I've grown to equate for(;;) with "infinite loop", whereas while(true) I have to stop and think about. Perhaps its because I was coding C before there was a true. Back in the day we only had TRUE as a macro, and if something was buggy I'd have to go convince myself that the macro hasn't been redefined to 0 somehow (it happened!). With for(;;) there's no chance of that. If you insist on the while form, I'd almost rather see while (1). Of course then some might wonder if it isn't the letter l...
–
T.E.D.Jul 27 '10 at 19:24

1

@mphair: Yeah, if you take note of the text that the editor puts in when you italicize or codeify text, you can just type that directly into the comment field yourself. I've seen some folks put in hyperlinks, but that's a bit too hardcore for me.
–
T.E.D.Jul 27 '10 at 19:46

1

Adding to the while(1) and for(;;) disusion, I've seen code using for(EVER) with EVER defined to be ;;
–
asrJul 27 '10 at 20:33

1

@supercat: the only way that's faster than a "typical for" is if your compiler sucks. for(i=10;i;i--) should generate the same code and it's much more legible.
–
R..Jul 29 '10 at 19:43

This is sort of an indirect answer, but this question got me thinking about the logic behind it, and I thought this might be worth sharing.

As everyone else has said, you use a do ... while loop when you want to execute the body at least once. But under what circumstances would you want to do that?

Well, the most obvious class of situations I can think of would be when the initial ("unprimed") value of the check condition is the same as when you want to exit. This means that you need to execute the loop body once to prime the condition to a non-exiting value, and then perform the actual repetition based on that condition. What with programmers being so lazy, someone decided to wrap this up in a control structure.

So for example, reading characters from a serial port with a timeout might take the form (in Python):

The added benefit for languages that create a new scope for loops: char_read does not pollute the function namespace. But note also that there is a better way to do this, and that is by using Python's None value:

So here's the crux of my point: in languages with nullable types, the situation initial_value == exit_value arises far less frequently, and that may be why you do not encounter it. I'm not saying it never happens, because there are still times when a function will return None to signify a valid condition. But in my hurried and briefly-considered opinion, this would happen a lot more if the languages you used did not allow for a value that signifies: this variable has not been initialised yet.

This is not perfect reasoning: in reality, now that null-values are common, they simply form one more element of the set of valid values a variable can take. But practically, programmers have a way to distinguish between a variable being in sensible state, which may include the loop exit state, and it being in an uninitialised state.

Like I said, I know how they work, I just wasn't sure in what case one makes sense over the other.
–
mphairJul 27 '10 at 19:48

It's logical that you use the do {} while when you know for sure that you have to pass at least once trough the loop. Like for instance if you have a function that finds an element in an array and you've previously put an if array.IsEmpty() then return; . If it passed that check you can safely use do {} while. do-while is also easy to think of, as a repetitive loop : "I eat until I'm satisfied" translates to do {eat();} while (!satisfied();). Testing the condition before the loop, is considered safer.. and that's why it's used more often.
–
Ioan Paul PirauJul 27 '10 at 20:09

The answers so far summarize the general use for do-while. But the OP asked for an example, so here is one: Get user input. But the user's input may be invalid - so you ask for input, validate it, proceed if it's valid, otherwise repeat.

With do-while, you get the input while the input is not valid. With a regular while-loop, you get the input once, but if it's invalid, you get it again and again until it is valid. It's not hard to see that the former is shorter, more elegant, and simpler to maintain if the body of the loop grows more complex.

I think the reason I've never used them for this is I usually end up telling the user what was wrong with their input. Which means the conditional would be in the center of a loop and I would just break if the input is correct.
–
mphairJul 27 '10 at 19:46

@mphair: Actually, for that sort of situation I might sometimes be more inclined to use a "do {} while(0);" loop, using "continue;" if the user's input is unacceptable. If there's only one problem and message, using "do {} while(1);" and "break;" works nicely, but if there are multiple reasons to demand re-entry, the "continue;" construct works out more nicely.
–
supercatJul 28 '10 at 4:26

Here's my theory why most people (including me) prefer while(){} loops to do{}while(): A while(){} loop can easily be adapted to perform like a do..while() loop while the opposite is not true. A while loop is in a certain way "more general". Also programmers like easy to grasp patterns. A while loop says right at start what its invariant is and this is a nice thing.

Here's what I mean about the "more general" thing. Take this do..while loop:

do {
A;
if (condition) INV=false;
B;
} while(INV);

Transforming this in to a while loop is straightforward:

INV=true;
while(INV) {
A;
if (condition) INV=false;
B;
}

Now, we take a model while loop:

while(INV) {
A;
if (condition) INV=false;
B;
}

And transform this into a do..while loop, yields this monstrosity:

if (INV) {
do
{
A;
if (condition) INV=false;
B;
} while(INV)
}

Now we have two checks on opposite ends and if the invariant changes you have to update it on two places. In a certain way do..while is like the specialized screwdrivers in the tool box which you never use, because the standard screwdriver does everything you need.

Replacing a "do {} while(x);" loop into a "while(x);" loop requires that X either be a condition that can be easily "primed", or that it be "naturally" true on the first pass. To me, priming statements before a loop imply that something within the loop needs priming, and a while(x) {};" loop implies that the loop may execute zero times. If I want a loop that will execute at least once, I use a "do {} while(x);" loop.
–
supercatJul 28 '10 at 4:31

while loops check the condition before the loop, do...while loops check the condition after the loop. This is useful is you want to base the condition on side effects from the loop running or, like other posters said, if you want the loop to run at least once.

I understand where you're coming from, but the do-while is something that most use rarely, and I've never used myself. You're not doing it wrong.

You're not doing it wrong. That's like saying someone is doing it wrong because they've never used the byte primitive. It's just not that commonly used.

I've used a do while when I'm reading a sentinel value at the beginning of a file, but other than that, I don't think it's abnormal that this structure isn't too commonly used--do-whiles are really situational.

The most common scenario I run into where I use a do/while loop is in a little console program that runs based on some input and will repeat as many times as the user likes. Obviously it makes no sense for a console program to run no times; but beyond the first time it's up to the user -- hence do/while instead of just while.

This allows the user to try out a bunch of different inputs if desired.

I suspect that software developers use do/while less and less these days, now that practically every program under the sun has a GUI of some sort. It makes more sense with console apps, as there is a need to continually refresh the output to provide instructions or prompt the user with new information. With a GUI, in contrast, the text providing that information to the user can just sit on a form and never need to be repeated programmatically.

Supporting comments anywhere in the file would be trivial (and simplify the code overall) if you just put if (line[0]=='#') continue; right after the read_line call in your main while loop...
–
R..Jul 29 '10 at 19:53

I can't see how I would implement your suggestion to find a header. (dang, can't figure out how to format code in the comments, plz help!) header = false; while (! header) { line = read_line(); if (line[0]=='#') continue; header = true; } this is clearer/simpler to you?
–
fliesAug 19 '10 at 15:53

One of the applications I have seen it is in Oracle when we look at result sets.

Once you a have a result set, you first fetch from it (do) and from that point on.. check if the fetch returns an element or not (while element found..) .. The same might be applicable for any other "fetch-like" implementations.

DOWHILE (no shutdown requested)
determine timeout
wait for work(timeout)
IF (there is work)
REPEAT
process
UNTIL(wait for work(0 timeout) indicates no work)
do what is supposed to be done at end of busy period.
ENDIF
ENDDO

the REPEAT UNTIL(cond) being a do {...} while(!cond)

Sometimes the wait for work(0) can be cheaper CPU wise (even eliminating the timeout calculation might be an improvement with very high arrival rates). Moreover, there are many queuing theory results that make the number served in a busy period an important statistic. (See for example Kleinrock - Vol 1)

where check for and do other work may be exhorbitively expensive to put in the main loop or perhaps a kernel that does not support an efficient waitany(waitcontrol*,n) type operation or perhaps a situation where a prioritized queue might starve the other work and throttle is used as starvation control. This type of balancing can seem like a hack but it can be necessary. Blind use of thread pools would entirely defeat the performance benefits of the use of a caretaker thread with a private queue for a high updating rate complicated data structure as the use of a thread pool rather than a caretaker thread would require thread-safe implementation.

I really don't want to get into a debate about the pseudo code (eg whether shutdown requested should be tested in the UNTIL) or caretaker threads versus thread pools - this is just meant to give a flavor of a particular use case of the control flow structure.

I am programming about 12 years and only 3 months ago I have met a situation where it was really convenient to use do-while as one iteration was always necessary before checking a condition. So guess your big-time is ahead :).

Nearly everytime I've seen a do...while it was because of a lack of understanding of the problem and involved some terrible hack. There are exceptions, but generally speaking, if you've got a do...while, you should rethink what you're doing... :-)
–
Brian KnoblauchJul 27 '10 at 19:47

2

If you where right then do-while would be excluded from all programming languages in order to not confuse programmers :).
–
NarekJul 27 '10 at 19:59