While Statements
A while statement is a control flow statement used to repeatedly execute a block of code as long as a specified condition is true.
Condition must be of type bool.
Tip
The condition in a while loop can also be written within parentheses.
The condition is evaluated initially. If the condition is false from the beginning, the code block is skipped, and the program continues executing the next line of code after the while loop.
After executing the code block, the condition is re-evaluated. If the condition is still true, the code block is executed again. This process continues until the condition becomes false.
Once the condition becomes false, the program exits the while loop, and execution continues with the next line of code after the while statement.
/*
* Copyright ©2026 Michael R. Bernstein. All new modifications licensed under Apache 2.0.
* Upstream lineage ©2023 governed by original BSD 3-Clause. See README.md.
*/
fn while_loop() -> u32 {
var counter: u32 = 0;
while counter < 5 {
// Increment the counter
counter = counter + 1;
}
return counter;
}