When is a do-while appropriate?

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


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.