15
votes

When is a do-while the better choice over other types of loops? What are some common scenarios where its better than others?

I understand the function of a do-while, but not when to use it.

13
I'm sure I've seen this question before. Can't find a dupe, though.Nosredna
@Hardwareguy Not at all. It just occurred to me while I was working on something that I haven't used it in my entire project.Alex S
Yeah, I find I hardly ever use it. Even in some cases where I know the loop must be done once before I check the condition, the first iteration is a special case in some way, so it makes more sense to place it outside of the loop block altogether.Sean
You should clarify it's a loop with test at the end. VB6/VBA has a "Do While ... Loop" syntax that tests at the beginning of the loop.DJ.

13 Answers

57
votes

When you need something done at least once, but don't know the number of times prior to initiating the loop.

4
votes

It's not often that it's the best thing to use, but one scenario is when you must do something at least once, but any further iterations are dependent on some condition.

do {
    //do something
} while ( condition );
4
votes

No-one's yet mentioned its use in C macros...

#define do_all(x) do{ foo(x); bar(x); baz(x); } while(0)

then in the code you can have

do_all(a);
  • the point being that it gets executed exactly once and the semi-colon on the end of the macro call completes the while(0); statement.
3
votes

I've used it before if I need to implement lots of conditional checks, for example processing an input form in php. Probably not the best practice, but it's more readable than many alternatives:

do {
   if ( field1_is_invalid ) {
      $err_msg = "field1 is invalid"; break;
   }

   if ( field2_is_invalid ) {
      $err_msg = "field2 is invalid"; break;
   }

   .. check half a dozen more things ..

   // Only executes if all checks succeed.
   do_some_updates();

} while (false)

Also, I guess this isn't technically a loop. More like a way of avoiding using GOTO :)

3
votes

I usually use a do-while when something needs to happen, but it won't necessarily happen "correctly" on the first time. For instance:

int x;
do
{
    x = random.next(100);
    cout << x << endl;
} while (x != 13);

In this case, the x you start with doesn't matter at all, because it's overwritten.

2
votes

It's appropriate when you would like to have your condition checked at the end of the loop execution. Hence the loop will always run at least once and then it will verify if it should iterate further.

1
votes

When it is more appropriate to do something and then evaluate the boolean expression...or as Brian said...when you need something done at least once. This syntax moves the evaluation of the boolean expression to after the loop instead of before the loop.

1
votes

Whenever what is in the loop needs to be executed at least once.

1
votes

I've long held that do-while is not used in C-based languages as much as it should be because the reuse of the "while" keyword is awkward and confusing. Pascal's repeat-until does not share any keywords with its while-begin-end structure.

I'd love to analyze a big heap of code someday and see if do-while is underrepresented in C code compared to similar constructs in other languages.

1
votes

do while() loops while a condition is true, but on the other hand, Pascal's repeat until loops while a condition is false (both will run at least once).

When I program in Pascal I almost always use repeat until.
When I program in C++ I almost always use while() {}.

I can't explain why, but I feel it's normal. Weird?

1
votes

when reading from a file or waiting for a connection to be established (other human interaction as well), anything for what the number of iterations is not known a priori (e.g. number of records returned by an sql query), or when you do steps of different size (e.g. read 1 or 5 lines from the file depending on the last one read), when going over all combinations/permutations of objects, whenever 'for' loop conditions become cumbersome

1
votes

Another exception when you are doing something recursive, like the following with reading inner exceptions:

catch(Exception exc)
{
    Exception currentException = exc;
    do
    {
        Console.WriteLine(string.Format("{0}: {1}", currentException.GetType().Name, currentException.Message));
    } while((currentException = currentException.InnerException) != null);
}
1
votes

Normally when you need the user to input some value, the counter variable is based on the input value, you use do-while. //The following code is in C++. It requires the user to input a number and repeats until users input number larger than 0.

do{
    cout << "Enter a Positive integer: ";
    cin >> num;
}while( num < 0 );