117

Possible Duplicates:
While vs. Do While
When should I use do-while instead of while loops?

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

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

9
  • 57
    For what it's worth, after a decade of programming as my career, I've used a do-while loop like once or twice.
    – Matt Greer
    Jul 27, 2010 at 19:11
  • 1
    @Matt - That does make me feel better. At least it means that I'm not alone.
    – mphair
    Jul 27, 2010 at 19:12
  • 3
    I'll second Matt and add another decade or so to that. I rarely ever use the do-while loop either. Jul 27, 2010 at 19:32
  • MANY duplicates. Here's one that links to a bunch of them: stackoverflow.com/questions/3094972/…
    – gnovice
    Jul 27, 2010 at 19:53
  • 3
    The correct “master question” seems to be stackoverflow.com/questions/224059/… Jul 28, 2010 at 8:39

31 Answers 31

148

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.

do
{
   try to access resource...
   put up message box with retry option

} while (user says retry);
14
  • 5
    So I guess this would follow under the "I haven't run into that circumstance."
    – mphair
    Jul 27, 2010 at 19:11
  • 10
    honestly, i very rarely run into a circumstance when I just need to use a do..while..
    – Stan R.
    Jul 27, 2010 at 19:12
  • 1
    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. Jul 27, 2010 at 19:14
  • 1
    I've used them from time to time too, though rarely. After a bit they usually get refactored into a normal while loop as well - just because the areas around it changed and made a do...while more clumsy than it first was.
    – Joshua
    Jul 27, 2010 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.
    – anon
    Jul 27, 2010 at 19:20
82

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

6
  • 10
    +1 for adding relevant technical information to the choice between loop forms. Jul 27, 2010 at 19:34
  • 2
    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.
    – JeremyP
    Jul 28, 2010 at 16:10
  • 3
    @Jeremy: The jump you speak of is outside the loop, it isn't executed N times.
    – Ben Voigt
    Jul 28, 2010 at 23:58
  • 1
    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 Voigt
    Jul 29, 2010 at 4:35
  • @BenVoigt I know your comment is a decade old by now, but Duff's Device should not be mentioned without the very important caveat - it's become less efficient on modern compilers, because modern compilers can usually intelligently unroll straightforward loops themselves as optimal for the target machine, while they generally do not have logic for figuring out the intent of a Duff's Device and thus can't optimize it nearly as well. Which is a great lesson about optimizing code for some target machine instead of for an abstract "sufficiently advanced optimizer".
    – mtraceur
    Oct 30, 2019 at 16:21
15

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:

do
{
    //do calculator logic here
    //prompt user for continue here
} while(cont==true);//cont is short for continue
4
  • 3
    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.
    – Joshua
    Jul 27, 2010 at 19:23
  • 9
    continue is a keyword ;D Jul 27, 2010 at 20:05
  • Atrinithis: Lol... I slipped up. Thanks for correcting me there.
    – thyrgle
    Jul 27, 2010 at 20:10
  • == true is not needed. cont == true if cont is true returns true. That's totally useless. Apr 16, 2019 at 17:33
13

I have used this in a TryDeleteDirectory function. It was something like this

do
{
    try
    {
        DisableReadOnly(directory);
        directory.Delete(true);
    }
    catch (Exception)
    {
        retryDeleteDirectoryCount++;
    }
} while (Directory.Exists(fullPath) && retryDeleteDirectoryCount < 4);
7
  • Nice. This is the first example that actually makes sense to be wrapped in a do...while.
    – Joshua
    Jul 27, 2010 at 19:28
  • 6
    Why/how is this better than a standard while? Jul 27, 2010 at 19:33
  • The loop will always execute once, so you might want to do something, then try it again if it fails. If you use a normal while loop, you'll be checking if it fails before you've even done it on the first iteration.
    – NibblyPig
    Jul 27, 2010 at 19:38
  • 1
    @SLC But wouldn't you want to check if the directory exists before-hand anyways? Jul 27, 2010 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.
    – NibblyPig
    Jul 27, 2010 at 20:02
11

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

response_buffer = []
char_read = port.read(1)

while char_read:
    response_buffer.append(char_read)
    char_read = port.read(1)

# When there's nothing to read after 1s, there is no more data

response = ''.join(response_buffer)

Note the duplication of code: char_read = port.read(1). If Python had a do ... while loop, I might have used:

do:
    char_read = port.read(1)
    response_buffer.append(char_read)
while char_read

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:

response_buffer = []
char_read = None

while char_read != '':
    char_read = port.read(1)
    response_buffer.append(char_read)

response = ''.join(response_buffer)

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.

5
  • This is one of the more interesting responses I've read here. Nice contribution.
    – Bob Moore
    Dec 23, 2013 at 9:56
  • The two versions are not equivalent. If the first read returns None, the while version correctly does not add anything to the response buffer, but your do version always adds something. Dec 17, 2016 at 16:10
  • @DavidStone read() shouldn't ever return None. If you're using a library where it does, the premise doesn't apply (ie. that the sentinel value is not in the set of possible check values).
    – detly
    Dec 18, 2016 at 11:02
  • With your latest edit, I see what I should have said is '' instead of None. Some sort of value that evaluates to false. Chalk it up to my unfamiliarity with Python's read function. Dec 26, 2016 at 17:09
  • @DavidStone I don't understand. If read() returns '', nothing will be appended to the string, it's empty.
    – detly
    Dec 26, 2016 at 18:22
7

It's as simple as that:

precondition vs postcondition

  • while (cond) {...} - precondition, it executes the code only after checking.
  • do {...} while (cond) - postcondition, code is executed at least once.

Now that you know the secret .. use them wisely :)

2
  • 1
    Like I said, I know how they work, I just wasn't sure in what case one makes sense over the other.
    – mphair
    Jul 27, 2010 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. Jul 27, 2010 at 20:09
7

I used them a fair bit when I was in school, but not so much since.

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.

14
  • 6
    Out of curiosity...why "for(;;)" instead of "while(true)"?
    – mphair
    Jul 27, 2010 at 19:20
  • 4
    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, 2010 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, 2010 at 19:46
  • 2
    @T.E.D.: My preferred notation for loop-until-explicit-exit is "do{}while(1);". Incidentally, in embedded systems work, my normal loop paradigm is "i=10; do {} while(--i);". For tight loops, that's much faster than a typical for(); I figure it's more readable to use that consistently as the loop pattern when an up-count isn't needed than to arbitrarily use for() in non-performance-critical cases.
    – supercat
    Jul 27, 2010 at 20:10
  • 2
    Adding to the while(1) and for(;;) disusion, I've seen code using for(EVER) with EVER defined to be ;;
    – asr
    Jul 27, 2010 at 20:33
6

A situation where you always need to run a piece of code once, and depending on its result, possibly more times. The same can be produced with a regular while loop as well.

rc = get_something();
while (rc == wrong_stuff)
{
    rc = get_something();
}

do
{
    rc = get_something();
}
while (rc == wrong_stuff);
6

do while is if you want to run the code block at least once. while on the other hand won't always run depending on the criteria specified.

4

I see that this question has been adequately answered, but would like to add this very specific use case scenario. You might start using do...while more frequently.

do
{
   ...
} while (0)

is often used for multi-line #defines. For example:

#define compute_values     \
   area = pi * r * r;      \
   volume = area * h

This works alright for:

r = 4;
h = 3;
compute_values;

-but- there is a gotcha for:

if (shape == circle)  compute_values;

as this expands to:

if (shape == circle) area = pi *r * r;
volume = area * h;

If you wrap it in a do ... while(0) loop it properly expands to a single block:

if (shape == circle)
  do
  {
    area = pi * r * r;
    volume = area * h;
  } while (0);
4

I like to understand these two as:
while -> 'repeat until',
do ... while -> 'repeat if'.

2

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.

2
  • 1
    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.
    – mphair
    Jul 27, 2010 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.
    – supercat
    Jul 28, 2010 at 4:26
2

I've used it for a reader that reads the same structure multiple times.

using(IDataReader reader = connection.ExecuteReader())
{
    do
    {
        while(reader.Read())
        {
            //Read record
        }
    } while(reader.NextResult());
}
2

I can't imagine how you've gone this long without using a do...while loop.

There's one on another monitor right now and there are multiple such loops in that program. They're all of the form:

do
{
    GetProspectiveResult();
}
while (!ProspectIsGood());
1

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.

-- file --
5
Joe
Bob
Jake
Sarah
Sue

-- code --
int MAX;
int count = 0;
do {
MAX = a.readLine();
k[count] = a.readLine();
count++;
} while(count <= MAX)
1

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.

1
  • 1
    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.
    – supercat
    Jul 28, 2010 at 4:31
1

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

4
  • 1
    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... :-) Jul 27, 2010 at 19:47
  • 2
    If you where right then do-while would be excluded from all programming languages in order to not confuse programmers :).
    – Narek
    Jul 27, 2010 at 19:59
  • @Narek: It's been close to seven more years since you wrote this, have you had more circumstances where do while was a better solution without regrets?
    – chqrlie
    Jun 24, 2017 at 16:56
  • Yes, probably one more time :D
    – Narek
    Jul 7, 2017 at 11:19
1

It is a quite common structure in a server/consumer:

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

Similarly:

DOWHILE (no shutdown requested)
   determine timeout
   wait for work(timeout)
   IF (there is work)
      set throttle
      REPEAT
          process
      UNTIL(--throttle<0 **OR** wait for work(0 timeout) indicates no work)
   ENDIF
   check for and do other (perhaps polled) work.
ENDDO

where check for and do other work may be exorbitantly 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 (for example, 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.

1

Even though there are plenty of answers here is my take. It all comes down to optimalization. I'll show two examples where one is faster then the other.

Case 1: while

string fileName = string.Empty, fullPath = string.Empty;

while (string.IsNullOrEmpty(fileName) || File.Exists(fullPath))
{
    fileName = Guid.NewGuid().ToString() + fileExtension;
    fullPath = Path.Combine(uploadDirectory, fileName);
}

Case 2: do while

string fileName = string.Empty, fullPath = string.Empty;

do
{
    fileName = Guid.NewGuid().ToString() + fileExtension;
    fullPath = Path.Combine(uploadDirectory, fileName);
}
while (File.Exists(fullPath));

So there two will do the exact same things. But there is one fundamental difference and that is that the while requires an extra statement to enter the while. Which is ugly because let's say every possible scenario of the Guid class has already been taken except for one variant. This means I'll have to loop around 5,316,911,983,139,663,491,615,228,241,121,400,000 times. Every time I get to the end of my while statement I will need to do the string.IsNullOrEmpty(fileName) check. So this would take up a little bit, a tiny fraction of CPU work. But do this very small task times the possible combinations the Guid class has and we are talking about hours, days, months or extra time?

Of course this is an extreme example because you probably wouldn't see this in production. But if we would think about the YouTube algorithm, it is very well possible that they would encounter the generation of an ID where some ID's have already been taken. So it comes down to big projects and optimalization.

1

This is my personal opinion, but this question begs for an answer rooted in experience:

  • I have been programming in C for 38 years, and I never use do / while loops in regular code.

  • The only compelling use for this construct is in macros where it can wrap multiple statements into a single statement via a do { multiple statements } while (0)

  • I have seen countless examples of do / while loops with bogus error detection or redundant function calls.

  • My explanation for this observation is programmers tend to model problems incorrectly when they think in terms of do / while loops. They either miss an important ending condition or they miss the possible failure of the initial condition which they move to the end.

For these reasons, I have come to believe that where there is a do / while loop, there is a bug, and I regularly challenge newbie programmers to show me a do / while loop where I cannot spot a bug nearby.

This type of loop can be easily avoided: use a for (;;) { ... } and add the necessary termination tests where they are appropriate. It is quite common that there need be more than one such test.

Here is a classic example:

/* skip the line */
do {
    c = getc(fp);
} while (c != '\n');

This will fail if the file does not end with a newline. A trivial example of such a file is the empty file.

A better version is this:

int c;  // another classic bug is to define c as char.
while ((c = getc(fp)) != EOF && c != '\n')
    continue;

Alternately, this version also hides the c variable:

for (;;) {
    int c = getc(fp);
    if (c == EOF || c == '\n')
        break;
}

Try searching for while (c != '\n'); in any search engine, and you will find bugs such as this one (retrieved June 24, 2017):

In ftp://ftp.dante.de/tex-archive/biblio/tib/src/streams.c , function getword(stream,p,ignore), has a do / while and sure enough at least 2 bugs:

  • c is defined as a char and
  • there is a potential infinite loop while (c!='\n') c=getc(stream);

Conclusion: avoid do / while loops and look for bugs when you see one.

4
  • 1
    I prefer avoiding while() {} loops, because they are safer in terms of initial checks, so tends to make you "brain off", lazy to think on better algorithm, put a tons of unnesesary error checking, so on.. "Lack of do{}while() usage" is a sign of bad(brainless) or a newbie programmer, produce lower quality and slower code. So I first ask myself "Is it a strictly while() {} case?" If not - I just will try to write do while loop, despite it could require more thinking and input data accuracy
    – xakepp35
    Sep 13, 2019 at 8:53
  • I understand your answer but I could think of some possible scenario's where this would actually be better. Please look at while: prnt.sc/v2zy04 or at do while: prnt.sc/v2zyka. I haven't been programmer for as long as you have but I couldn't find a bug in there. It's pretty clear that the do while is cleaner because it doesn't require the extra check on the while to enter the loop. If we are talking about optimizing code then I'd say that is pretty clean.
    – Roy Berris
    Oct 20, 2020 at 11:16
  • @RoyBerris: your example is interesting. In a C program, the functions used inside the loop would require extra tests to ensure they did not fail. This would add extra clutter and break or return statements. Turning the do/while loop into a for(;;) loop be more consistent IMHO. My ostracism towards this statement is similar to my refusal to use strncpy() even in the rare cases where it would be the right tool: don't let casual readers imagine that these constructions are harmless, because in most cases they are sources of hard to find bugs.
    – chqrlie
    Nov 2, 2020 at 13:21
  • @chqrlie seeing the original answer was about any C language I guess both answers would do. C# is a lot "saver" then their predecessors, so it would technically be faster with the do while.
    – Roy Berris
    Nov 3, 2020 at 14:26
0

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.

0

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.

do
{
   int input = GetInt("Enter any integer");
   // Do something with input.
}
while (GetBool("Go again?"));

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.

0

I use do-while loops all the time when reading in files. I work with a lot of text files that include comments in the header:

# some comments
# some more comments
column1 column2
  1.234   5.678
  9.012   3.456
    ...     ...

i'll use a do-while loop to read up to the "column1 column2" line so that I can look for the column of interest. Here's the pseudocode:

do {
    line = read_line();
} while ( line[0] == '#');
/* parse line */

Then I'll do a while loop to read through the rest of the file.

2
  • 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... Jul 29, 2010 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?
    – flies
    Aug 19, 2010 at 15:53
0

Being a geezer programmer, many of my school programming projects used text menu driven interactions. Virtually all used something like the following logic for the main procedure:

do
    display options
    get choice
    perform action appropriate to choice
while choice is something other than exit

Since school days, I have found that I use the while loop more frequently.

0

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.

0

I 've used it in a function that returned the next character position in an utf-8 string:

char *next_utf8_character(const char *txt)
{
    if (!txt || *txt == '\0')
        return txt;

    do {
        txt++;
    } while (((signed char) *txt) < 0 && (((unsigned char) *txt) & 0xc0) == 0xc0)

    return (char *)txt;
}

Note that, this function is written from mind and not tested. The point is that you have to do the first step anyway and you have to do it before you can evaluate the condition.

1
0

Any sort of console input works well with do-while because you prompt the first time, and re-prompt whenever the input validation fails.

0

Even in educational references you barely would find a do...while example. Only recently, after reading Ethan Brown beautiful book, Learning JavaScript I encountered one do...while well defined example. That's been said, I believe it is OK if you don't find application for this structure in you routine job.

0

It's true that do/while loops are pretty rare. I think this is because a great many loops are of the form

while(something needs doing)
    do it;

In general, this is an excellent pattern, and it has the usually-desirable property that if nothing needs doing, the loop runs zero times.

But once in a while, there's some fine reason why you definitely want to make at least one trip through the loop, no matter what. My favorite example is: converting an integer to its decimal representation as a string, that is, implementing printf("%d"), or the semistandard itoa() function.

To illustrate, here is a reasonably straightforward implementation of itoa(). It's not quite the "traditional" formulation; I'll explain it in more detail below if anyone's curious. But the key point is that it embodies the canonical algorithm, repeatedly dividing by 10 to pick off digits from the right, and it's written using an ordinary while loop... and this means it has a bug.

#include <stddef.h>

char *itoa(unsigned int n, char buf[], int bufsize)
{
    if(bufsize < 2) return NULL;
    char *p = &buf[bufsize];
    *--p = '\0';

    while(n > 0) {
        if(p == buf) return NULL;
        *--p = n % 10 + '0';
        n /= 10;
    }

    return p;
}

If you didn't spot it, the bug is that this code returns nothing — an empty string — if you ask it to convert the integer 0. So this is an example of a case where, when there's "nothing" to do, we don't want the code to do nothing — we always want it to produce at least one digit. So we always want it to make at least one trip through the loop. So a do/while loop is just the ticket:

    do {
        if(p == buf) return NULL;
        *--p = n % 10 + '0';
        n /= 10;
    } while(n > 0);

So now we have a loop that usually stops when n reaches 0, but if n is initially 0 — if you pass in a 0 — it returns the string "0", as desired.

As promised, here's a bit more information about the itoa function in this example. You pass it arguments which are: an int to convert (actually, an unsigned int, so that we don't have to worry about negative numbers); a buffer to render into; and the size of that buffer. It returns a char * pointing into your buffer, pointing at the beginning of the rendered string. (Or it returns NULL if it discovers that the buffer you gave it wasn't big enough.) The "nontraditional" aspect of this implementation is that it fills in the array from right to left, meaning that it doesn't have to reverse the string at the end — and also meaning that the pointer it returns to you is usually not to the beginning of the buffer. So you have to use the pointer it returns to you as the string to use; you can't call it and then assume that the buffer you handed it is the string you can use.

Finally, for completeness, here is a little test program to test this version of itoa with.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int n;
    if(argc > 1)
        n = atoi(argv[1]);
    else {
        printf("enter a number: "); fflush(stdout);
        if(scanf("%d", &n) != 1) return EXIT_FAILURE;
    }

    if(n < 0) {
        fprintf(stderr, "sorry, can't do negative numbers yet\n");
        return EXIT_FAILURE;
    }

    char buf[20];
    printf("converted: %s\n", itoa(n, buf, sizeof(buf)));

    return EXIT_SUCCESS;
}
-1

I ran across this while researching the proper loop to use for a situation I have. I believe this will fully satisfy a common situation where a do.. while loop is a better implementation than a while loop (C# language, since you stated that is your primary for work).

I am generating a list of strings based on the results of an SQL query. The returned object by my query is an SQLDataReader. This object has a function called Read() which advances the object to the next row of data, and returns true if there was another row. It will return false if there is not another row.

Using this information, I want to return each row to a list, then stop when there is no more data to return. A Do... While loop works best in this situation as it ensures that adding an item to the list will happen BEFORE checking if there is another row. The reason this must be done BEFORE checking the while(condition) is that when it checks, it also advances. Using a while loop in this situation would cause it to bypass the first row due to the nature of that particular function.

In short:

This won't work in my situation.

    //This will skip the first row because Read() returns true after advancing.
    while (_read.NextResult())
           {
               list.Add(_read.GetValue(0).ToString());
           }

   return list;

This will.

    //This will make sure the currently read row is added before advancing.
    do
        {
            list.Add(_read.GetValue(0).ToString());
        } 
        while (_read.NextResult());

    return list;
1
  • SQLDataReader usage would be nested loops. The inner one calls Read() and should be a while loop, since the first Read() call accesses the first row. The outer one calls NextResult() and should be a do-while, because the first result dataset is active prior to the first NextResult() call. The code snippets don't make much sense, especially because the comments both don't match the code and are wrong.
    – Ben Voigt
    Oct 30, 2019 at 17:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.