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,
When you need something done at least once, but don't know the number of times prior to initiating the loop.
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.
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 );
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 :)
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.
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.