Conditionally executes a statement repeatedly.
[edit] Syntax attr (optional)while (
condition )
statement [edit] Condition
A condition can either be an expression or a simple declaration.
When control reaches condition, the condition will yield a value, which is used to determine whether statement will be executed.
[edit] ExpressionIf condition is an expression, the value it yields is the the value of the expression contextually converted to bool. If that conversion is ill-formed, the program is ill-formed.
[edit] DeclarationIf condition is a simple declaration, the value it yields is the value of the decision variable (see below) contextually converted to bool. If that conversion is ill-formed, the program is ill-formed.
[edit] Non-structured binding declarationThe declaration has the following restrictions:
=
assignment-expressionThe decision variable of the declaration is the declared variable.
[edit] ExplanationA while statement is equivalent to
/* label */:
{
if (
condition )
{
goto
/* label */ ;
}
}
If condition is a declaration, the variable it declares is destroyed and created with each iteration of the loop.
If the loop needs to be terminated within statement, a break statement can be used as terminating statement.
If the current iteration needs to be terminated within statement, a continue statement can be used as shortcut.
[edit] NotesRegardless of whether statement is a compound statement, it always introduces a block scope. Variables declared in it are only visible in the loop body, in other words,
while (--x >= 0) int i; // i goes out of scope
is the same as
while (--x >= 0) { int i; } // i goes out of scope
As part of the C++ forward progress guarantee, the behavior is undefined if a loop that is not a trivial infinite loop(since C++26) without observable behavior does not terminate. Compilers are permitted to remove such loops.
[edit] Keywords [edit] Example#include <iostream> int main() { // while loop with a single statement int i = 0; while (i < 10) i++; std::cout << i << '\n'; // while loop with a compound statement int j = 2; while (j < 9) { std::cout << j << ' '; j += 2; } std::cout << '\n'; // while loop with a declaration condition char cstr[] = "Hello"; int k = 0; while (char c = cstr[k++]) std::cout << c; std::cout << '\n'; }
Output:
[edit] See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4