Programming Search⌘K

Conceptintro

Do-while loop

Also called do-while loop, do while, do statement, post-test loop, exit-controlled loop, repeat until, repeat-until loop, do-until loop, do while 0.

A do-while loop runs its body first and tests its condition after each pass, so the body always runs at least once. Pascal and Lua call it repeat-until.

Applies to
core-languages

Idea

Some loops must run their body before they can test anything. A program that asks for a password must ask once before it can check the answer, and a function that prints the digits of a number must print at least one digit, even for 0. A do-while loop runs the body, then tests the condition, and runs the body again while the condition is true.

# Python has no do-while loop. The usual form is while True with a test at the end.
answers = iter(["", "abc", "42"])
tries = 0
while True:
    text = next(answers)
    tries += 1
    if text.isdigit():
        break
print("got", text, "after", tries, "tries")

# A post-test loop runs once even when the condition is false at the start.
n = 10
while True:
    print("pass with n =", n)
    n += 1
    if not n < 5:
        break

# The same loop as a pre-test loop does not run at all.
n = 10
while n < 5:
    print("never printed")
    n += 1
print("done")
Output
got 42 after 3 tries
pass with n = 10
done

The first loop reads answers until one is a number, and it must read an answer before it can test it. The second loop has the condition n < 5, which is false at the start, but the body runs once because the test comes after it. The third loop has the same condition at the top, so its body never runs.

How it works

Run, then test. Wikipedia calls this form a post-test loop: "the body is executed and afterwards the condition is checked. If it holds the body is run again and then the condition is checked"1. In Java, "The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false"2, and "Executing a do statement always executes the contained Statement at least once"2. C# puts the difference from while in one line: "a do loop executes one or more times. The do loop differs from the while loop, which executes zero or more times"3. The Kotlin documentation says it plainly: "the body of do-while runs at least once, regardless of the condition"4.

The syntax. C, C++, Java, C# and JavaScript write do body while (condition);. The semicolon at the end is required. MDN notes that it "requires a semicolon at the end, but the automatic semicolon insertion process may insert one for you"5 in JavaScript. In C++, "When control reaches a do statement, its statement will be executed unconditionally"6.

continue goes to the test. In a do-while loop, continue does not jump to the top of the body. It jumps to the condition. MDN says that continue "stops statement execution and re-evaluates condition"5. If the condition is false, the loop ends.

Repeat-until. Pascal and Lua turn the condition around. In Lua, "a repeat-until statement repeats its body until its condition is true. The test is done after the body, so the body is always executed at least once"7. Free Pascal says that repeat executes its statements "up to the moment when Expression evaluates to True"8. Pascal writes repeat a := a + 1 until a = 10;9.

Languages without it. Python, Go and Rust have no do-while loop. They write an endless loop with the test at the end of the body: while True: and if not cond: break in Python, for { ... if !cond { break } } in Go and loop { ... if !cond { break } } in Rust. Python rejected a do clause in PEP 315. Later attempts "did not meet with success because no syntax emerged that could compete with the following form", the while True loop with an if-break, and "Users of the language are advised to use the while-True form with an inner if-break when a do-while loop would have been appropriate"10.

In languages

LanguageVerdictNote
PythonIdiom
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the do...while loop of JavaScript, which runs its body before it tests the condition. No example file exists.
GoIdiom
RustIdiom
KotlinNativeKotlin has do { } while (condition), whose body runs at least once. No example file exists because kotlinc is not installed.
SQLIdiomA query has no loops. PL/pgSQL has LOOP with EXIT WHEN as the last statement, which tests after the body.
BashIdiomBash has no do-while loop. The body can go into the condition list of a while loop with an empty body, because the exit status of the last command decides. No example file exists.
PowerShellNativePowerShell has do { } while (condition) and do { } until (condition), which both test after the body. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no loops.
CSSDoes not applyCSS has no loops.
Regular expressionsDoes not applyA regular expression has no loops with conditions. Quantifiers repeat a part of a pattern.
Language Verdict Mechanism
Python idiom no do-while; while True: with if not cond: break at the end of the body
JavaScript native do { } while (condition);
TypeScript native the do...while loop of JavaScript
Java native do { } while (condition); with a boolean condition
Kotlin native do { } while (condition)
C# native do { } while (condition);
Go idiom no do-while; for { ...; if !cond { break } }
Rust idiom no do-while; loop { ...; if !cond { break } }
C native do statement while (expression);; do { } while (0) in macros
C++ native do statement while (expression);
Bash idiom no do-while; while body; condition; do :; done puts the body in the condition list
PowerShell native do { } while (condition) and do { } until (condition)
SQL idiom no loops in queries; LOOP with EXIT WHEN at the end in PL/pgSQL
Regex n/a no loops with conditions
HTML n/a no loops
CSS n/a no loops

The do-while loop is the least used of the loops, and three of the newer languages, Go, Rust and Python, leave it out. They write it as an endless loop with an exit at the end. The languages of the C family keep do ... while, and Pascal and Lua have the until form.

The example files show these differences. Python uses while True with a break at the end. JavaScript shows that continue jumps to the test and retries an action until it works. Java counts digits and gets 1 for 0, where a while loop gets 0. C# reads commands until quit and follows the Collatz rule from 1. Go and Rust write the post-test loop with for and loop and a break at the end. Go also sets a Boolean in the post statement of a three-part for, and Rust puts the body in the condition of a while. C uses do { } while (0) in a macro. C++ converts numbers to a base, so 0 gives the string "0".

PythonGitHub
def digits(n):
    # The body runs before the test, so 0 has one digit.
    count = 0
    while True:
        n //= 10
        count += 1
        if n == 0:
            break
    return count


print([digits(n) for n in (0, 7, 42, 1000)])

# A retry loop tries at least once and stops after a limit.
attempts = iter([False, False, True])
tries = 0
while True:
    tries += 1
    ok = next(attempts)
    if ok or tries >= 5:
        break
print("ok" if ok else "failed", "after", tries, "tries")
Output
[1, 1, 2, 4]
ok after 3 tries
  • Verdict: idiom. Python has no do-while loop, and PEP 315, which proposed one, was rejected. while True: with if ...: break as the last statement of the body is the post-test loop, so digits(0) is 1 and the retry loop makes at least one try.
#include <algorithm>
#include <print>
#include <string>

std::string to_base(unsigned n, unsigned base) {
    const char* digits = "0123456789abcdef";
    std::string out;
    do {
        out.push_back(digits[n % base]);
        n /= base;
    } while (n != 0);
    std::ranges::reverse(out);
    return out;
}

int main() {
    for (unsigned n : {0u, 10u, 255u}) {
        std::println("{}: base 2 {}, base 16 {}", n, to_base(n, 2), to_base(n, 16));
    }

    // A post-test loop runs once even if the condition is false.
    int x = 10;
    do {
        std::println("x = {}", x);
        ++x;
    } while (x < 5);
}
Output
0: base 2 0, base 16 0
10: base 2 1010, base 16 a
255: base 2 11111111, base 16 ff
x = 10
  • Verdict: native. to_base must make at least one digit, so it uses a do loop, and 0 gives the string "0". A while loop with the same body would give an empty string for 0.
JavaGitHub
public class Main {
    static int digitsDo(int n) {
        int count = 0;
        do {
            n /= 10;
            count++;
        } while (n != 0);
        return count;
    }

    static int digitsWhile(int n) {
        int count = 0;
        while (n != 0) {
            n /= 10;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        for (int n : new int[] {0, 5, 12345, -987}) {
            System.out.println(n + ": do " + digitsDo(n) + ", while " + digitsWhile(n));
        }
    }
}
Output
0: do 1, while 0
5: do 1, while 1
12345: do 5, while 5
-987: do 3, while 3
  • Verdict: native. The two methods differ only in the place of the test. For 0, the do loop runs its body once and gives 1, the right number of digits, and the while loop never runs and gives 0. Integer division in Java rounds toward zero, so negative numbers also reach 0.
#include <stdio.h>

/* do { } while (0) makes the macro act as one statement. */
#define SWAP(a, b) do { int tmp_ = (a); (a) = (b); (b) = tmp_; } while (0)

int main(void) {
    int x = 1, y = 2;
    if (x < y)
        SWAP(x, y);
    else
        printf("no swap\n");
    printf("x=%d y=%d\n", x, y);

    /* Copy a string with its null character: the body runs before the test. */
    const char *src = "loop";
    char dst[8];
    int k = 0;
    do {
        dst[k] = src[k];
    } while (src[k++] != '\0');
    printf("copied \"%s\" with %d bytes\n", dst, k);
    return 0;
}
Output
x=2 y=1
copied "loop" with 5 bytes
  • Verdict: native. do statement while (expression); tests after the body. The SWAP macro is wrapped in do { } while (0), so SWAP(x, y); with its semicolon is one statement and the else still belongs to the if. The copy loop copies the null character too, because the test comes after the copy.
var reader = new StringReader("add\nlist\nquit\nignored\n");
string? command;
do
{
    command = reader.ReadLine();
    Console.WriteLine($"command: {command}");
} while (command != "quit");

// The Collatz rule from 1: the do loop makes one round, the while loop none.
int n = 1, steps = 0;
do
{
    n = n % 2 == 0 ? n / 2 : 3 * n + 1;
    steps++;
} while (n != 1);
Console.WriteLine($"do: {steps} steps");

n = 1;
steps = 0;
while (n != 1)
{
    n = n % 2 == 0 ? n / 2 : 3 * n + 1;
    steps++;
}
Console.WriteLine($"while: {steps} steps");
Output
command: add
command: list
command: quit
do: 3 steps
while: 0 steps
  • Verdict: native. The first loop must read a command before it can test it, so command is declared before the loop and the do form fits. The two Collatz loops have the same condition, but from 1 the do loop goes 1, 4, 2, 1 in 3 steps, and the while loop does nothing.
JavaScriptGitHub
// continue jumps to the condition, not to the top of the body.
let i = 0;
const seen = [];
do {
  i++;
  if (i % 2 === 0) continue;
  seen.push(i);
} while (i < 7);
console.log(seen.join(" "));

// A retry loop: the body runs before the first test.
const results = ["timeout", "timeout", "ok"];
let attempt = 0;
let result;
do {
  result = results[attempt];
  attempt++;
  console.log(`attempt ${attempt}: ${result}`);
} while (result !== "ok" && attempt < 5);

// The condition is false at the start, but the body runs once.
let n = 10;
do {
  console.log("n =", n);
  n++;
} while (n < 5);
Output
1 3 5 7
attempt 1: timeout
attempt 2: timeout
attempt 3: ok
n = 10
  • Verdict: native. do { } while (condition); tests after the body. A continue goes to the test i < 7, so the loop does not skip its exit, and result is declared before the loop because the condition must see it.
package main

import "fmt"

func main() {
	// for with the test at the end of the body is the do-while loop of Go.
	n, digits := 0, 0
	for {
		n /= 10
		digits++
		if n == 0 {
			break
		}
	}
	fmt.Println("digits of 0:", digits)

	// Reverse the digits of a number.
	m, rev := 1200, 0
	for {
		rev = rev*10 + m%10
		m /= 10
		if m == 0 {
			break
		}
	}
	fmt.Println("reversed 1200:", rev)

	// A three-part for whose condition is set at the end of each pass.
	x := 10
	for ok := true; ok; ok = x < 5 {
		fmt.Println("x =", x)
		x++
	}
}
Output
digits of 0: 1
reversed 1200: 21
x = 10
  • Verdict: idiom. Go has only for, and no do-while form. An endless for with if ... { break } as its last statement is the post-test loop. The last loop uses a Boolean that starts as true and gets the real condition in the post statement, so the body runs once before the first real test.
RustGitHub
fn main() {
    // loop with the test at the end of the body.
    let mut n: u32 = 0;
    let mut digits = 0;
    loop {
        n /= 10;
        digits += 1;
        if n == 0 {
            break;
        }
    }
    println!("digits of 0: {digits}");

    // The body goes into the condition block of a while loop with an empty body.
    let mut x = 10;
    while {
        println!("x = {x}");
        x += 1;
        x < 5
    } {}

    // loop gives a value with break.
    let answers = ["no", "no", "yes"];
    let mut tries = 0;
    let answer = loop {
        let a = answers[tries];
        tries += 1;
        if a == "yes" {
            break a;
        }
    };
    println!("{answer} after {tries} tries");
}
Output
digits of 0: 1
x = 10
yes after 3 tries
  • Verdict: idiom. Rust has no do-while loop. loop with if ... { break; } at the end is the usual form, and break a gives the loop a value. The condition of while is an expression, so a block can hold the body and end with the test, but this form is hard to read.
  • Loop and a half. Many loops need the test in the middle of the body, not at the end: read, test, process. See loop and a half.
  • Until loops. repeat ... until c is do ... while (!c). Bash also has an until loop, but it tests first, so it is a while loop.
  • do { } while (0) in C macros. A macro with several statements, wrapped in do { ... } while (0), acts as one statement, so if (x) MACRO(); else ... compiles and works. The loop runs exactly once.
  • Retry loops. A loop that tries an action and repeats on failure tries at least once, so it is a natural post-test loop. Add a limit on the number of tries.

Pitfalls

  • The body runs for bad input. A do-while loop runs its body before it checks anything, so the body must handle the case that a while loop would skip, such as an empty list.
  • A missing semicolon. In C, C++, Java and C#, do { } while (x) without ; is a syntax error, and in JavaScript automatic semicolon insertion hides the mistake.
  • continue skips to the test. A continue that skips the update of a counter at the end of the body can make the loop run forever.
  • Scope of variables. In C, Java and C#, a variable declared in the body is not visible in the condition, so it must be declared before the loop.
  • Reversed conditions. When code moves from repeat ... until c to do ... while, the condition must become !c.

Cost

A do-while loop is the cheapest loop for the machine: the body falls through to one test and one conditional jump back. Compilers often turn a while loop into a test before the loop and a do-while loop after it, for this reason. The difference is one jump for each loop, so the choice between the forms is about meaning, not speed.

History

FORTRAN 77 brought "DO loop extensions, including parameter expressions, negative increments, and zero trip counts"11, so a DO loop with an empty range runs zero times. Niklaus Wirth improved ALGOL W, "releasing this as Pascal in 1970"9. Pascal has repeat ... until, a post-test loop with the condition to stop, and C has do ... while with the condition to go on. Wikipedia notes a trap in the names: the term do-while loop "can be confusing since Fortran and PL/I use the syntax "DO WHILE" for pre-test loops"1.

References

  1. Loop (statement), Wikipedia, Post-test loop; Equivalent constructs
  2. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.13 The do Statement
  3. Iteration statements, C# language reference, The do statement
  4. Conditions and loops, Kotlin documentation, While loops
  5. do...while, MDN Web Docs, Introduction; Description
  6. do-while loop, C++ reference, cppreference.com, Explanation
  7. Roberto Ierusalimschy, Programming in Lua, first edition, 4.3.3 Repeat, 4.3.3
  8. The Repeat..until statement, Free Pascal Reference Guide, the whole page
  9. Pascal (programming language), Wikipedia, History; Control structures
  10. PEP 315, Enhanced While Loop, Notice
  11. Fortran, Wikipedia, FORTRAN 77

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/EWSEVV/text.yaml