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.

ADTC
  • 679
  • 2
  • 8
  • 16
  • 3
    See Stack Overflow: [do…while vs while](http://stackoverflow.com/questions/3347001/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](http://codereview.stackexchange.com/questions/31893/differences-between-using-a-do-while-vs-while-and-initializing-variables) –  Jan 06 '15 at 03:55
  • "avoid asking subjective questions where … every answer is equally valid..." ([help/dont-ask]) – gnat Jan 06 '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/dont-ask]) – ADTC Jan 06 '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. –  Jan 06 '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 07 '15 at 04:38
  • I also don't believe that *having very large answer lists will **always** weaken the utility of the question*. Knowledge is **not** limited to every question having a *single* right answer. That is perhaps only a small part of all knowledge that can be gathered. Many questions can have many answers for each question, and they are all equally valid. Having that many answers available to a reader will broaden their knowledge horizon further by giving them various different perspectives from different people, different industries, or different parts of the world. – ADTC Jan 07 '15 at 04:47

5 Answers5

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.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • 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 06 '15 at 04: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 06 '15 at 04:09
  • 7
    This isn't a polling place. Come up with your own examples. – Robert Harvey Jan 06 '15 at 04:12
  • 2
    Since OP asked for examples, and you refuse to supply one, I must downvote this answer. – user949300 Jan 06 '15 at 05: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 06 '15 at 12:29
  • @Gusdor An open source example was asked here due to the nature of the answer. I don't ask for commercial examples in the question, but rather for simple examples (see other answers) that show commercial **or** non-commercial applications of the construct. For this answer, I wanted examples of widely used CLI that demonstrably use the construct in their code. It's easier to showcase open source examples for it than commercial closed source ones. **It's a pity that the answerer is unwilling to expand his answer with one.** – ADTC Jan 06 '15 at 14:03
  • @Gusdor And no, *"any time you want the loop to always execute at least once"* is *not* **the** answer. I did not ask what the purpose and intended use of the construct is, but rather for showcases of where such a purpose is fulfilled, and the intended use demonstrated, in the real world. Those are two different things. – ADTC Jan 06 '15 at 14:08
18

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.

Gort the Robot
  • 14,733
  • 4
  • 51
  • 60
  • 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 06 '15 at 12:43
  • If writing this do-while loop as a while loop I would unroll the first pass. – Taemyr Jan 06 '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 06 '15 at 14:06
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.)

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
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.

sea-rob
  • 6,841
  • 1
  • 24
  • 47
  • How did it go back to `a()`? – ADTC Jan 06 '15 at 04: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) – sea-rob Jan 06 '15 at 04: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.

CodesInChaos
  • 5,697
  • 4
  • 19
  • 26
pdx9k9e9
  • 29
  • 2
  • 3
    But what does `do-while` loops have to do with pre-processor macros? – ADTC Jan 06 '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 07 '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 09 '15 at 04:40
  • 1
    @ADTC This is [a well-known idiom](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Multi-statement_Macro) 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