Post-Test Loop
Image: Taylor, CC BY-SA 4.0, Wikimedia Commons
In short: A loop where the exit condition is only checked AFTER the loop body — this guarantees the code block runs at least once, regardless of whether the condition was ever true at all.
In more detail: A classic example is do...while. Useful for cases where an action always has to happen at least once, before it can even be checked whether it should be repeated — such as a menu prompt that only decides whether to show again after the first display. In contrast, the pre-test loop checks the condition upfront and can skip the body entirely.
In Depth
The name describes the position of the condition check in the loop structure: “post” stands for the end of the loop body, where the condition is checked (“do { … } while (…)”), as opposed to the “pre” at the start for the pre-test loop.
do {
show_menu()
choice = ask_user()
} while choice != "exit"The decisive practical difference: for a post-test loop, the body is guaranteed to run at least once, because the condition is only checked for the first time after the first iteration has already happened. This is suitable whenever the condition logically can’t be evaluated at all BEFORE the first iteration — for example because the data needed for it (a user input, a menu selection value) is only produced by the loop body itself.
For a normal, pre-test loop, this “guaranteed first iteration” would have to be artificially forced, either by duplicating the code’s execution before the loop, or via a condition variable specially initialized so the first check always turns out true — both add unnecessary complexity that a post-test loop avoids by nature.
Post-test loops are overall rarer than pre-test loops, because the use case (“the body has to run at least once”) is more specific than the standard case (“the body should run zero to any number of times, depending on a condition checkable upfront”). Typical use cases: interactive menus, input validation (see do-while loop), or network protocols where at least one attempt has to be made before any result is even available for evaluation.
See also: Pre-Test Loop, do-while Loop, Loops