<p>One somewhat rarely used, but still occasionally handy, feature of many programming languages is <code>do ... while</code> loops:</p>
<pre><code>var position;

do {
    position = random_coords();
} while (is_inside_wall(position));
</code></pre>
<p>A <code>do ... while</code> is similar to a normal <code>while</code> loop, except that the body runs once before the condition is ever checked.</p>
<p>I've noticed Rust, a language that generally has well-thought-through syntax, omits this. Thus, it seems likely there are some disadvantages of <code>do ... while</code> loops.</p>
<p>What are the pros and cons of <code>do ... while</code>?</p>

<control-flow><while-loop><do-while>
What are the pros and cons of having do ... while loops?
CC BY-SA 4.0
2023-05-17T20:22:44.827Z
Scala 3 got rid of do while loops, suggesting people use `while { ...body; cond } {}` instead of the old `while (cond) {...body}`. Looks a lot uglier than do while loops, though
user
CC BY-SA 4.0
2023-05-17T20:23:42.003Z
@user ...yeah. That just feels like trying to force people to use a fancy new feature or sth
rydwolf
CC BY-SA 4.0
2023-05-17T20:37:29.277Z
@RydwolfPrograms It's not about forcing people to use a fancy new feature, but it is *because* of a fancy new (and IMO useless) feature. They added a `while cond do ...body` syntax (no parens or braces), and since `do` is now used for that, it can't be used for do while loops. The `while { ...body; cond } {}` thing is something that was always possible in Scala, since blocks are expressions
user
CC BY-SA 4.0
2023-07-06T10:57:36.323Z
For some reason, I really like `do ... while` loops, and if I ever see an excuse to use one I jump on it. No idea why. They're just weirdly fun to me.
TRiG
CC BY-SA 4.0
2023-07-14T00:02:20.440Z
Related: https://langdev.stackexchange.com/questions/1815/
Karl Knechtel
CC BY-SA 4.0
2023-05-16T19:06:25.843Z
The question title doesn't match the question in the body.  "What are the pros and cons..." vs "what are some ... disadvantages of...".
Ari Brodsky
CC BY-SA 4.0
2023-05-16T19:06:59.250Z
@AriBrodsky Ah my bad. I'm asking about both pros and cons, will edit once my school's fire drill's over
rydwolf
CC BY-SA 4.0
2023-05-16T19:23:37.163Z
Some APLs have repeat…until besides for while…endwhile and allow mix-and-match, inluding repeat…endrepeat and while…until
Adám
<p>This construct, which expresses the logic that the block should be executed once unconditionally and then further iterated on a certain condition, typically has a very unhappy syntax in any language that supplies it.</p>
<p>Placing the test at the end of the block defies the general principle that control logic goes at the header of the block.</p>
<p>But placing the logic in the header tends to suggest the condition is evaluated on entry, and there doesn't seem to be a good word that expresses a <code>DoOnceThenWhile</code> block.</p>
<p>And if the test is brought to the header but only tried after the first iteration, then the rules around scoping of any variable used in the test is also not necessarily obvious - can it refer to variables declared below and inside the block, or must it pre-emptively declare?</p>
<p>Finally in terms of problems, there are still algorithms where the test must occur somewhere in the middle of the block (assuming that entry occurs strictly at the top), so there's still a residuum not fully catered for.</p>
<p>Having put some thought into this in the past, my preference would be for special syntax along the following lines:</p>
<pre><code>While Unbroken
    position = random_coords()
    ....
    Break When not(is_inside_wall(position))
    ....
End While
</code></pre>
<p>The key points here being that the <code>While Unbroken</code> explicitly identifies this as a looping construct where at least some part of the block is executed unconditionally, but with special logic inside that determines the exact point of the test and break (without contrivances like <code>While True</code> or <code>While 1=1</code>), and <code>Break When</code> is supplied as a conditional break statement (with the main word 'break' appearing leftmost).</p>
<p>This then caters for both middle-breaking and end-breaking cases.</p>
<p>Most if not all languages already have the basic facilities (such as the ability to express indefinite loops and break out conditionally), if not the specific keywords.</p>

CC BY-SA 4.0
2023-07-08T19:24:08.187Z
2023-07-08T19:24:08.187Z
Steve
<h2>Pro: Loop-invariant code hoisting</h2>
<p>Suppose there's some loop-invariant code in your loop. Your compiler would just love to move that code out of the loop so it's evaluated only once.</p>
<p>With a <code>do</code>-<code>while</code> loop, you know that the body of the loop will be executed at least once, so the invariant code will always be needed.</p>
<pre class="lang-c prettyprint-override"><code>do {
    loop_invariant_code();
    other_code();
} while (cond);

/* This is the same! */
loop_invariant_code();
do {
    other_code();
} while (cond);
</code></pre>
<p>In a <code>while</code> loop, the condition could be false on the <em>first</em> iteration, so the body may not be executed. In this case, moving the loop invariant code may not be safe (e.g. it might fail in some way, such as a division by zero), or it may significantly slow the &quot;no iterations&quot; case.</p>
<pre class="lang-c prettyprint-override"><code>while (cond) {
    loop_invariant_code();
    other_code();
}

/* You'll have to optimise it to something more like this. */
if (cond) {
    loop_invariant_code();
    do {
        other_code();
    } while (cond);
}
</code></pre>

CC BY-SA 4.0
2023-07-12T02:18:01.143Z
2023-07-12T02:18:01.143Z
Pseudonym
<p>There's one &quot;con&quot; I haven't seen mentioned.  One can make an argument that, for most condition-based loops, the condition in question is a pre-condition that must be met for evaluation of the body to be a valid operation.  When a programmer uses a <code>do .. while</code> loop, it's rarely the case that the precondition isn't met at all.  Instead, <strong>EITHER</strong> the rest of the code guarantees the precondition <strong>is</strong> met and so a <code>while</code> loop could have been used but the programmer is just optimizing away the first, redundant test <strong>OR</strong> the precondition takes a slightly different form, possibly requiring a bit of setup prior to starting the <code>while</code> loop which wouldn't strictly be necessary if we skipped the first test of the condition, so again the programmer is avoiding a little inconvience by skipping the check.</p>
<p>This suggests that a <code>while</code> construct might be the &quot;safer&quot; option -- easier to reason about and less fragile in the face of changes to the surrounding code.  So, a language designer might take a &quot;<code>do ... while</code> considered harmful&quot; approach and leave it out of their language for that reason.</p>
<p>Bjarne Stroustrup makes a comment along these lines in &quot;The C++ Programming Language&quot; (see the quote in <a href="https://stackoverflow.com/questions/994905/is-there-ever-a-need-for-a-do-while-loop">this Stack Overflow question</a>).  I thought I'd read something similar from Guido van Rossum regarding Python's lack of a <code>do .. while</code> statement, too, but all I can find is his general call to reject a <code>do .. while</code> PEP on more general grounds of inelegance and potential confusion (see <a href="https://mail.python.org/pipermail/python-ideas/2013-June/021610.html" rel="nofollow noreferrer">this post</a>).</p>

CC BY-SA 4.0
2023-07-11T22:00:40.143Z
2023-07-11T22:00:40.143Z
K. A. Buhr
CC BY-SA 4.0
2023-07-11T22:26:22.417Z
I think the reverse of this is actually true; for the same reason a `do .. while` is bad and inelegant for checking preconditions, a normal `while` is bad for postconditions, which is the primary use case of `do .. while`. E.g., generating a random ID that doesn't conflict with an existing one, or a random set of coordinates that isn't inside of a solid object.
rydwolf
CC BY-SA 4.0
2023-07-11T23:10:01.050Z
Actually, `while` loops are quite good at testing postconditions.  The postcondition for the loop exit is the logical negation of the precondition for the loop body, and the body won't be executed if the postcondition is already met.  The potential problem with a `do .. while` loop is that it may execute the loop body when the postcondition is already satisfied and -- if it does -- then what's the meaning of the "postcondition"?  If it's valid for the loop body to be executed when the postcondition is already met, maybe the safest programs are those where every loop is infinite.  ;)
K. A. Buhr
CC BY-SA 4.0
2023-07-11T23:17:31.990Z
But in, e.g., either of the cases I mentioned, you either know for a fact that whatever initial value you start with is invalid, or wouldn't want to assume a default value even if it does meet the postcondition (e.g. if you initialize the random ID to `0` before a `while` instead of a `do .. while`, you can predict the first random ID will always be `0`, which could be a security issue). I see what you're saying regarding safety/semantic meaning, I just don't think it's a big issue since typically you only use `do .. while` in places where it really does make more sense than `while`.
rydwolf
CC BY-SA 4.0
2023-07-12T06:03:42.987Z
Iterate-to-fixpoint is the classic example where `do`/`while` makes more sense than `while`.
Pseudonym
<p>The main difference between <code>while</code> and <code>do ... while</code> is when the loop condition is checked. For <code>while</code>, the condition is checked <strong>before</strong> the first iteration, while for <code>do ... while</code> it is checked <strong>after</strong> at least one iteration has been executed. Hence a developer selects the type of loop depending from the task. Both cases exist and are not artificial, for instance</p>
<ul>
<li>if the list is too long, we truncate it by removing elements. Maybe the list is not too long? Using <code>do ... while</code>  would require an extra <code>if</code> for checking if we should start removing the elements starting from, resulting more bulky and complex code.</li>
<li>we read records from the file. We may get either the next record or end of file marker, but we need to attempt reading before we get either of these two. Here <code>do ... while</code> is much more natural, even if we could simulate it with <code>while(true) { ... if (eof) break }</code> that needs more attention from the reader.</li>
</ul>
<p>Hence I think no big harm to have both types of the loop in the language.</p>

CC BY-SA 4.0
2023-07-11T17:44:18.107Z
2023-07-11T18:43:50.943Z
2023-07-11T18:43:50.943Z
Audrius Meškauskas
<h1>Odd syntax</h1>
<p>This is primarily a design issue, but <code>do...while</code> loops have odd syntax which might be an issue in languages like Python which use indentation. Not necessarily a deal-breaker, but definitely something to consider if your language uses indentation.</p>

CC BY-SA 4.0
2023-05-16T18:53:33.490Z
2023-05-16T18:53:33.490Z
Ginger
CC BY-SA 4.0
2023-05-19T06:04:30.947Z
There's an interesting ergonomic benefit to the `do while (condition) { code }` syntax. If the programmer decided they need to switch from while to do-while, it's a 3 character change. Re-arranging the do-while in other languages is significantly more effort.
springogeek
CC BY-SA 4.0
2023-07-08T19:47:15.553Z
@SilvioMayolo C-style for loops already evaluate the third part of the header at the end and it doesn't seem to confuse anyone.
xigoi
CC BY-SA 4.0
2023-07-08T20:08:00.547Z
@xigoi On the contrary I'd argue C-style `for` loops should *also* go the way of the dinosaur. Python did it right: `for`-each loops are the norm, and you have to use `while` for anything complex.
Silvio Mayolo
CC BY-SA 4.0
2023-07-11T18:38:55.460Z
@SilvioMayolo: It would be difficult to add foreach loops to C itself because C doesn't really have arrays, just pointers in trench coats.
dan04
CC BY-SA 4.0
2023-05-16T18:57:31.687Z
Perhaps `do while (condition) { code }` would be a way to get around this? Could be more easily confused with a normal `while`, tho
rydwolf
CC BY-SA 4.0
2023-05-16T19:06:52.107Z
@RadvylfPrograms Putting the condition in front and evaluating it at the end seems like a huge recipe for footguns.
Silvio Mayolo
CC BY-SA 4.0
2023-05-16T19:16:12.243Z
@SilvioMayolo Not necessarily, you just need to change how you think about it from "evaluate the condition at the end" to "a normal `while` loop where you run the block an extra time at the start"
rydwolf
<p><code>do ... while</code> loops are more natural at the intermediate representation level. A <code>while</code> loop, naively, has to be implemented as two jumps.</p>
<pre><code>while (X) {
  Y
  Z
}
</code></pre>
<p>This must be implemented at a low-level as something like this.</p>
<pre><code>loop:
  X
  jump_if_false end_loop
  Y
  Z
  jump loop
end_loop:
</code></pre>
<p>A <code>do ... while</code> loop, on the other hand, is always exactly one conditional jump, even with no optimizations applied.</p>
<p>For example,</p>
<pre><code>do {
  X
  Y
} while (Z);
</code></pre>
<p>can be written as:</p>
<pre><code>loop:
  X
  Y
  Z
  jump_if_true loop
</code></pre>
<p>Now a good optimizer can help you with this, but in a low-level language it might make a big difference.</p>

CC BY-SA 4.0
2023-05-16T18:54:38.453Z
2023-05-17T02:37:58.870Z
2023-05-17T02:37:58.870Z
Silvio Mayolo
CC BY-SA 4.0
2023-05-17T03:01:55.920Z
Just as a side note, it's also common to implement `while (X) { Y; }` as `goto loop_start; do { Y; loop_start: } while (X);` for a few reasons. You can align the top of the loop to a cache line boundary, for example.
Pseudonym
<h1>Pro: better fit between syntax and logic</h1>
<p>For some algorithms, do ... while loops are the most natural way to express the program logic and prevent code duplication. Consider the example mentioned in the question:</p>
<pre><code>do {
    position = random_coords();
} while (is_inside_wall(position));
</code></pre>
<p>That is, we want to pick a random position and then repick as long as the position is inside a wall.</p>
<p>If do ... while loops are not available, this code will probably be written as a while loop instead. The best way to translate the logic is not obvious. One could pull the initial pick out ahead of the loop:</p>
<pre><code>position = random_coords();
while (is_inside_wall(position)) {
    position = random_coords();
}
</code></pre>
<p>This code is pretty readable but violates the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">don't repeat yourself</a> maxim--not too badly in this case, but it gets worse if the body of the loop is more than one statement.</p>
<p>Alternately, we could use a sentinel value to &quot;disable&quot; the check on the first iteration. This could be a separate variable:</p>
<pre><code>var position_set = false;
while (!position_set || is_inside_wall(position)) {
    position = random_coords();
    position_set = true;
}
</code></pre>
<p>Or, in some cases, a known invalid value of the variable we're checking:</p>
<pre><code>position = null;
while (position == null || is_inside_wall(position)) {
    position = random_coords();
}
</code></pre>
<p>These approaches add complexity and obscure the real loop condition.</p>
<p>Finally, maybe the worst option (though one that I admit I have used before): write an infinite loop and break out of it once the condition is satisfied:</p>
<pre><code>while (true) {
    position = random_coords();
    if (!is_inside_wall(position)) {
        break;
    }
}
</code></pre>
<p>This obscures the algorithm even more severely and is highly prone to accidental infinite loops.</p>
<p>In any case, none of these while-loop options read as cleanly as the do ... while version.</p>

CC BY-SA 4.0
2023-05-16T20:35:41.237Z
2023-05-16T21:05:16.787Z
2023-05-16T21:05:16.787Z
DLosc
CC BY-SA 4.0
2023-05-16T21:02:49.627Z
Tbf the last one is more sensible than you give it credit for; I believe it's even the recommended approach for Rust. While it's possible to forget something and make an inf loop, that's true of regular `while`/`do-while`s too
rydwolf
CC BY-SA 4.0
2023-05-16T21:09:19.703Z
Huh, interesting--and you're right about infinite loops. I changed it to "maybe" the worst.
DLosc
CC BY-SA 4.0
2023-05-17T04:55:46.133Z
`while (is_inside_wall(position = random_coords()));`
RubenVerg
# What are the pros and cons of having do ... while loops?
Posted by: username_0 on 2023-05-16
One somewhat rarely used, but still occasionally handy, feature of many programming languages is do ... while loops:
var position;

do {
    position = random_coords();
} while (is_inside_wall(position));

A do ... while is similar to a normal while loop, except that the body runs once before the condition is ever checked.
I've noticed Rust, a language that generally has well-thought-through syntax, omits this. Thus, it seems likely there are some disadvantages of do ... while loops.
What are the pros and cons of do ... while?
**Tags:** control-flow while-loop do-while
> **Comments:**
> **username_4**: The question title doesn't match the question in the body.  "What are the pros and cons..." vs "what are some ... disadvantages of...".  
> **username_0**: @AriBrodsky Ah my bad. I'm asking about both pros and cons, will edit once my school's fire drill's over  
> **username_5**: Some APLs have repeat…until besides for while…endwhile and allow mix-and-match, inluding repeat…endrepeat and while…until  
> **username_1**: Scala 3 got rid of do while loops, suggesting people use `while { ...body; cond } {}` instead of the old `while (cond) {...body}`. Looks a lot uglier than do while loops, though  
> **username_0**: @user ...yeah. That just feels like trying to force people to use a fancy new feature or sth  
> **username_1**: @RydwolfPrograms It's not about forcing people to use a fancy new feature, but it is *because* of a fancy new (and IMO useless) feature. They added a `while cond do ...body` syntax (no parens or braces), and since `do` is now used for that, it can't be used for do while loops. The `while { ...body; cond } {}` thing is something that was always possible in Scala, since blocks are expressions  
> **username_2**: For some reason, I really like `do ... while` loops, and if I ever see an excuse to use one I jump on it. No idea why. They're just weirdly fun to me.  
> **username_3**: Related: https://langdev.stackexchange.com/questions/1815/  
---
## 7 answers
### Answer by username_13 on 2023-05-16. Score: 18
do ... while loops are more natural at the intermediate representation level. A while loop, naively, has to be implemented as two jumps.
while (X) {
  Y
  Z
}

This must be implemented at a low-level as something like this.
loop:
  X
  jump_if_false end_loop
  Y
  Z
  jump loop
end_loop:

A do ... while loop, on the other hand, is always exactly one conditional jump, even with no optimizations applied.
For example,
do {
  X
  Y
} while (Z);

can be written as:
loop:
  X
  Y
  Z
  jump_if_true loop

Now a good optimizer can help you with this, but in a low-level language it might make a big difference.
> **Comments:**
> **username_7** (2023-05-17): Just as a side note, it's also common to implement `while (X) { Y; }` as `goto loop_start; do { Y; loop_start: } while (X);` for a few reasons. You can align the top of the loop to a cache line boundary, for example.  
---
### Answer by username_15 on 2023-05-16. Score: 15
Pro: better fit between syntax and logic
For some algorithms, do ... while loops are the most natural way to express the program logic and prevent code duplication. Consider the example mentioned in the question:
do {
    position = random_coords();
} while (is_inside_wall(position));

That is, we want to pick a random position and then repick as long as the position is inside a wall.
If do ... while loops are not available, this code will probably be written as a while loop instead. The best way to translate the logic is not obvious. One could pull the initial pick out ahead of the loop:
position = random_coords();
while (is_inside_wall(position)) {
    position = random_coords();
}

This code is pretty readable but violates the don't repeat yourself maxim--not too badly in this case, but it gets worse if the body of the loop is more than one statement.
Alternately, we could use a sentinel value to "disable" the check on the first iteration. This could be a separate variable:
var position_set = false;
while (!position_set || is_inside_wall(position)) {
    position = random_coords();
    position_set = true;
}

Or, in some cases, a known invalid value of the variable we're checking:
position = null;
while (position == null || is_inside_wall(position)) {
    position = random_coords();
}

These approaches add complexity and obscure the real loop condition.
Finally, maybe the worst option (though one that I admit I have used before): write an infinite loop and break out of it once the condition is satisfied:
while (true) {
    position = random_coords();
    if (!is_inside_wall(position)) {
        break;
    }
}

This obscures the algorithm even more severely and is highly prone to accidental infinite loops.
In any case, none of these while-loop options read as cleanly as the do ... while version.
> **Comments:**
> **username_0** (2023-05-16): Tbf the last one is more sensible than you give it credit for; I believe it's even the recommended approach for Rust. While it's possible to forget something and make an inf loop, that's true of regular `while`/`do-while`s too  
> **username_15** (2023-05-16): Huh, interesting--and you're right about infinite loops. I changed it to "maybe" the worst.  
> **username_16** (2023-05-17): `while (is_inside_wall(position = random_coords()));`  
---
### Answer by username_10 on 2023-05-16. Score: 13
# Odd syntax

This is primarily a design issue, but `do...while` loops have odd syntax which might be an issue in languages like Python which use indentation. Not necessarily a deal-breaker, but definitely something to consider if your language uses indentation.
> **Comments:**
> **username_0** (2023-05-16): Perhaps `do while (condition) { code }` would be a way to get around this? Could be more easily confused with a normal `while`, tho  
> **username_13** (2023-05-16): @RadvylfPrograms Putting the condition in front and evaluating it at the end seems like a huge recipe for footguns.  
> **username_0** (2023-05-16): @SilvioMayolo Not necessarily, you just need to change how you think about it from "evaluate the condition at the end" to "a normal `while` loop where you run the block an extra time at the start"  
> **username_11** (2023-05-19): There's an interesting ergonomic benefit to the `do while (condition) { code }` syntax. If the programmer decided they need to switch from while to do-while, it's a 3 character change. Re-arranging the do-while in other languages is significantly more effort.  
> **username_12** (2023-07-08): @SilvioMayolo C-style for loops already evaluate the third part of the header at the end and it doesn't seem to confuse anyone.  
> **username_13** (2023-07-08): @xigoi On the contrary I'd argue C-style `for` loops should *also* go the way of the dinosaur. Python did it right: `for`-each loops are the norm, and you have to use `while` for anything complex.  
> **username_14** (2023-07-11): @SilvioMayolo: It would be difficult to add foreach loops to C itself because C doesn't really have arrays, just pointers in trench coats.  
---
### Answer by username_9 on 2023-07-11. Score: 3
The main difference between `while` and `do ... while` is when the loop condition is checked. For `while`, the condition is checked **before** the first iteration, while for `do ... while` it is checked **after** at least one iteration has been executed. Hence a developer selects the type of loop depending from the task. Both cases exist and are not artificial, for instance

* if the list is too long, we truncate it by removing elements. Maybe the list is not too long? Using `do ... while` would require an extra `if` for checking if we should start removing the elements starting from, resulting more bulky and complex code.
* we read records from the file. We may get either the next record or end of file marker, but we need to attempt reading before we get either of these two. Here `do ... while` is much more natural, even if we could simulate it with `while(true) { ... if (eof) break }` that needs more attention from the reader.

Hence I think no big harm to have both types of the loop in the language.
---
### Answer by username_6 on 2023-07-08. Score: 2
This construct, which expresses the logic that the block should be executed once unconditionally and then further iterated on a certain condition, typically has a very unhappy syntax in any language that supplies it.
Placing the test at the end of the block defies the general principle that control logic goes at the header of the block.
But placing the logic in the header tends to suggest the condition is evaluated on entry, and there doesn't seem to be a good word that expresses a DoOnceThenWhile block.
And if the test is brought to the header but only tried after the first iteration, then the rules around scoping of any variable used in the test is also not necessarily obvious - can it refer to variables declared below and inside the block, or must it pre-emptively declare?
Finally in terms of problems, there are still algorithms where the test must occur somewhere in the middle of the block (assuming that entry occurs strictly at the top), so there's still a residuum not fully catered for.
Having put some thought into this in the past, my preference would be for special syntax along the following lines:
While Unbroken
    position = random_coords()
    ....
    Break When not(is_inside_wall(position))
    ....
End While

The key points here being that the While Unbroken explicitly identifies this as a looping construct where at least some part of the block is executed unconditionally, but with special logic inside that determines the exact point of the test and break (without contrivances like While True or While 1=1), and Break When is supplied as a conditional break statement (with the main word 'break' appearing leftmost).
This then caters for both middle-breaking and end-breaking cases.
Most if not all languages already have the basic facilities (such as the ability to express indefinite loops and break out conditionally), if not the specific keywords.
---
### Answer by username_7 on 2023-07-12. Score: 2
Pro: Loop-invariant code hoisting
Suppose there's some loop-invariant code in your loop. Your compiler would just love to move that code out of the loop so it's evaluated only once.
With a do-while loop, you know that the body of the loop will be executed at least once, so the invariant code will always be needed.
do {
    loop_invariant_code();
    other_code();
} while (cond);

/* This is the same! */
loop_invariant_code();
do {
    other_code();
} while (cond);

In a while loop, the condition could be false on the first iteration, so the body may not be executed. In this case, moving the loop invariant code may not be safe (e.g. it might fail in some way, such as a division by zero), or it may significantly slow the "no iterations" case.
while (cond) {
    loop_invariant_code();
    other_code();
}

/* You'll have to optimise it to something more like this. */
if (cond) {
    loop_invariant_code();
    do {
        other_code();
    } while (cond);
}
---
### Answer by username_8 on 2023-07-11. Score: 2
There's one "con" I haven't seen mentioned. One can make an argument that, for most condition-based loops, the condition in question is a pre-condition that must be met for evaluation of the body to be a valid operation. When a programmer uses a `do .. while` loop, it's rarely the case that the precondition isn't met at all. Instead, **EITHER** the rest of the code guarantees the precondition **is** met and so a `while` loop could have been used but the programmer is just optimizing away the first, redundant test **OR** the precondition takes a slightly different form, possibly requiring a bit of setup prior to starting the `while` loop which wouldn't strictly be necessary if we skipped the first test of the condition, so again the programmer is avoiding a little inconvience by skipping the check.

This suggests that a `while` construct might be the "safer" option -- easier to reason about and less fragile in the face of changes to the surrounding code. So, a language designer might take a "`do ... while` considered harmful" approach and leave it out of their language for that reason.

Bjarne Stroustrup makes a comment along these lines in "The C++ Programming Language" (see the quote in [this Stack Overflow question](https://stackoverflow.com/questions/994905/is-there-ever-a-need-for-a-do-while-loop)). I thought I'd read something similar from Guido van Rossum regarding Python's lack of a `do .. while` statement, too, but all I can find is his general call to reject a `do .. while` PEP on more general grounds of inelegance and potential confusion (see [this post](https://mail.python.org/pipermail/python-ideas/2013-June/021610.html)).
> **Comments:**
> **username_0** (2023-07-11): I think the reverse of this is actually true; for the same reason a `do .. while` is bad and inelegant for checking preconditions, a normal `while` is bad for postconditions, which is the primary use case of `do .. while`. E.g., generating a random ID that doesn't conflict with an existing one, or a random set of coordinates that isn't inside of a solid object.  
> **username_8** (2023-07-11): Actually, `while` loops are quite good at testing postconditions.  The postcondition for the loop exit is the logical negation of the precondition for the loop body, and the body won't be executed if the postcondition is already met.  The potential problem with a `do .. while` loop is that it may execute the loop body when the postcondition is already satisfied and -- if it does -- then what's the meaning of the "postcondition"?  If it's valid for the loop body to be executed when the postcondition is already met, maybe the safest programs are those where every loop is infinite.  ;)  
> **username_0** (2023-07-11): But in, e.g., either of the cases I mentioned, you either know for a fact that whatever initial value you start with is invalid, or wouldn't want to assume a default value even if it does meet the postcondition (e.g. if you initialize the random ID to `0` before a `while` instead of a `do .. while`, you can predict the first random ID will always be `0`, which could be a security issue). I see what you're saying regarding safety/semantic meaning, I just don't think it's a big issue since typically you only use `do .. while` in places where it really does make more sense than `while`.  
> **username_7** (2023-07-12): Iterate-to-fixpoint is the classic example where `do`/`while` makes more sense than `while`.  
---
