6

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.

closed as too broad by user40980, gnat, Bart van Ingen Schenau, Blrfl, Tulains Córdova Jan 6 '15 at 14:12

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    See Stack Overflow: do…while vs while (and the questions that it is a duplicate of), Code Review: Differences between using a do-while vs. while and initializing variables – user40980 Jan 6 '15 at 3:55
  • "avoid asking subjective questions where … every answer is equally valid..." (help center) – gnat Jan 6 '15 at 13:33
  • Some subjective questions are allowed ... Constructive subjective questions: inspire answers that explain “why” and “how”; invite sharing experiences over opinions; are more than just mindless social fun (help center) – ADTC Jan 6 '15 at 13:44
  • 2
    @ADTC there is a difference between asking questions that are entirely the sharing of experiences and having a question where the sharing of an experience helps expand the answer that is already there. The core question written is that of a poll of user experiences - where everyone who has ever seen a do while can provide an answer. Such questions can get very large answer lists and the utility of the question as a becomes poor - no one can find the answer in there. At that point, its better to consider asking the question on a discussion oriented site instead. – user40980 Jan 6 '15 at 18:31
  • I cannot find any good site that has the format of Stack Exchange and allows subjective questions. Please suggest any you know. Forums are bad because they have a linear thread-chain of discussions and the topic keeps changing. The format here allows keeping focus of the thread on the primary topic (question), having responses directly to the topic (answers) and mini discussions on the responses and on the topic (comments). This gives a tree-like structure to the discussion with question for trunk, answers for branches and comments for leaves. Something a forum cannot have easily. :/ – ADTC Jan 7 '15 at 4:38
17

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.

  • 3
    another construct is often while (result = readData(buffer)) != EOF which I don't really like either. However, in your case, if you have to use the content of buffer, you still need to test the value of result first. – njzk2 Jan 6 '15 at 12:43
  • If writing this do-while loop as a while loop I would unroll the first pass. – Taemyr Jan 6 '15 at 13:54
  • 1
    But you're not doing anything with the data you're reading. Once you add this, do...while isn't a good match anymore. – CodesInChaos Jan 6 '15 at 14:06
22

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.

  • 1
    Can you show some example code from an actual open-source command-line interpreter that is popular and commonly used? I know what a do while construct does. I am curious how often you see it used in real-life situations. – ADTC Jan 6 '15 at 4:04
  • That's a nice example @RobY I want to see more of these. So far I have seen CLI, data validation and resource retry. – ADTC Jan 6 '15 at 4:09
  • 7
    This isn't a polling place. Come up with your own examples. – Robert Harvey Jan 6 '15 at 4:12
  • 2
    Since OP asked for examples, and you refuse to supply one, I must downvote this answer. – user949300 Jan 6 '15 at 5:31
  • 7
    @user949300 the OP requested open source examples in the comment but requests commercial examples in the question. I hope the OP is less vague in his/her design docs. To be clear, this question is precise and accurate - "any time you want the loop to always execute at least once." is the answer. – Gusdor Jan 6 '15 at 12:29
3
    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.)

  • This is nice! It would be useful when you want to "fill the gap". – ADTC Apr 23 '18 at 3:36
2

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

  • How did it go back to a()? – ADTC Jan 6 '15 at 4:15
  • ...it just did. There was some marker character that started the control structure... Forth is postfix, so I don't remember the exact syntax. But there was basically a marker at the start, some logic, the test, some more logic, and a marker at the end. A quick search on Forth should pull up an example. (I changed "while" to "loop" to avoid confusion with C-languages) – Rob Jan 6 '15 at 4:17
2

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.

  • 3
    But what does do-while loops have to do with pre-processor macros? – ADTC Jan 6 '15 at 14:16
  • All contributions above point out algorithmical reasons for a do-while-loop. In C you could write all types of programs avoiding for loop and just use while loop. But when you use a for, a while or a do-while loop, you as a programmer are trying to express what you ment to do. So its a hint for us humans. Why then limit this fact only to algorithmical facts. I use the do-while-loop, becasue I will have the compiler checking, if i put a ";" at the end of "expr(a);". If I had chosen to use a simple "#define expr(a) { /* staments */ }" construct the compiler would not complain about a missing ;. – pdx9k9e9 Jan 7 '15 at 20:13
  • So you need to use a do { } while (false) in your pre-processor macro to force your compiler to complain about a missing semicolon in your actual code? Sounds like a compiler bug. Have you reported it yet? – ADTC Jan 9 '15 at 4:40
  • 1
    @ADTC This is a well-known idiom in C and C++. Though I wouldn't say it's primary use is to enforce semicolons but to allow macros to be used like functions. See the link for a more detailed discussion. – 5gon12eder Sep 18 '15 at 10:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.