Question

When I see for and while loops all over production codes and mammoth projects, the last time I saw a do while loop is for a university assignment involving menu-based console input program. About 50 lines long, at most.

Have you seen real-world applications of the do while loop construct? In what way is such a construct, in your example, advantageous over for or while loops, or any other constructs?

Note: I am not looking for hypothetical scenarios, but actual usage applied in the commercial industry.

Était-ce utile?

La solution

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
        break

Both of which are uglier in my opinion.

When I mostly did C++ programming, I used the do-while all the time, in real, shipping applications.

Autres conseils

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.

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

@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 the expression was tested, and if it was true, execute b() and then back to a().

The upshot is, if you don't have the information you need to decide whether to loop, then do...while can be really handy.

The (clunky) work-around is something like

a = null
while (a == null)
  a = something()

...does the same thing, but that initial a = null always leaves a sour taste in my mouth.

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.

Licencié sous: CC-BY-SA avec attribution
scroll top