Tag Info

New answers tagged


I like to use do while loops for pre-processor macros in C/C++ without the trailing ;. If I forget the ;, the compiler will stop with an error. Example: #define expr(a) do { /* do something with a */ } while(false) Notice the missing ; at the end of the line. In your code, you have to write expr(a); with a semicolon. Otherwise compilation will fail. ...


int counter = 0; do { s = Formatter.formatWorkerId(counter++); } while(all.contains(s)); Finds the smallest syntactically correct worker ID that isn't already present in a set. (My uses of do tend to be confined to that kind of problem, where you definitely have to generate a value, but the very first test might already succeed.)


Real-world application, reading data from a file in blocks until end of file: do result = readData(buffer) while result != EOF Without do-while you have to do something like result = 0 # magic value that must not be EOF while result != EOF result = readData(buffer) or while true result = readData(buffer) if result == EOF ...


@RobertHarvey's answer is gold, but I'll throw in a fun twist on "do...while" and "while...do" In the Forth programming language, the looping was actually split up this way (conjuring up pseudocode based on Forth code from years, dare I say decades, ago) { a() } loop (expr()) { b() } ... so that a() was guaranteed to execute at least once, then ...


You use do while any time you want the loop to always execute at least once. A typical example of such usage is a command-line interpreter; the command line prompt will always be displayed at least once.

Top 50 recent answers are included