views:

451

answers:

12

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.

+37  A: 

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

Brian Rasmussen
Couldn't have said it simpler myself. +1
Gab Royer
But there are times when you don't need a do...while to do this, such as something like while(input.hasNext()), so this isn't necessarily a hard rule.
Thomas Owens
@Thomas Owens: Well, you can do every kind of loop you need with a simple for statement, so you don't need do/while per se, but I would say that if you want to express intend this is the situation where do/while fits perfectly.
Brian Rasmussen
+3  A: 

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 );
Sean Nyman
A: 

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.

Andrew Siemer
+1  A: 

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.

quosoo
A: 

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

Thomas
A: 

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.

Nosredna
+3  A: 

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

Eric Petroelje
Wouldn't just wrapping the same logic in a function and replacing breaks with returns be more readable? You can indicate which check went wrong in your return value too.
shylent
@shylent - yes it would, which is why I mentioned that it probably isn't a best practice. But it can come in useful from time to time.
Eric Petroelje
A: 

In some languages at least, you don't have to have the while() statement at the end of the loop. For example,

do 
    ....
while(test)
    ....
repeat

is a structure I find myself using occasionally. Sometimes it makes more sense formatting-wise to do it this way; I work in a database-centric language most of the time, where all the fields are simply separated by an iterator - meaning if a record exists, there is always at least one field. This structure works well for parsing that data. First, I navigate to the location of the data, have a while(data exists), and then process the data; then I loop back to the beginning.

For the curious, it's PICK DATA/Basic. (I had an example written in C, but apparently it doesn't compile as I thought. Sorry, C folks... You can always emulate the behavior with a break statement, though I can't really suggest it for readability reasons.)

SparroHawc
Your example above isn't C, although it resembles C. You can't do that in C.
David Thornley
expected ‘;’ before ‘{’ token
fortran
Reeeeeally. Huh. Somehow I was under the impression that this worked in more languages than it does.
SparroHawc
A: 

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?

Nick D
+1  A: 

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.

FryGuy
A: 

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

MadH
+1  A: 

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