CKTIS / C++
while — a loop with a pre-execution condition
A while loop checks its condition before each execution of its body. It repeats the body while the condition is true; if the condition is false initially, the body never runs. Termination usually requires changing the state used by the condition.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
while (condition) statement
while (condition) {
// statements
}while (condition) statement repeats a statement, testing condition before each execution. The condition is contextually converted to bool; an invalid conversion makes the program ill-formed. Unlike do ... while, the body may execute zero times.
The body is one statement, often a { ... } block. The condition is required. In C++23 it can be an expression or a declaration of one initialized variable; in the latter case, that variable's value is tested, and the variable is created and destroyed for every condition check, including the final unsuccessful one.
A continue targeting this loop skips the rest of the body and leads to another condition check. while has no automatic update step: skipping a necessary state change can prevent termination. break exits the innermost enclosing loop or switch, so a break inside a nested switch does not exit the outer loop.
Watch out for while (condition);: the semicolon is an empty body, and a following block is not part of the loop. In the example, --remaining decreases the counter after each printed value; the loop ends when it reaches 0.
This entry targets C++23. The source is an evolving working draft, not a frozen C++23 publication; its newer extensions must not automatically be attributed to that version. A repository compiler flag does not attest the production runtime.
Examples
#include <iostream>
int main() {
int remaining = 3;
while (remaining > 0) {
std::cout << remaining << '\n';
--remaining;
}
std::cout << "Done\n";
}
Result
3 2 1 Done
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.