Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A while loop is a pre-test control flow statement that repeatedly executes a target statement or block of code as long as a specified expression evaluates to true. Because the condition is evaluated before the loop body executes, the loop body will not execute at all if the initial condition evaluates to false.

Syntax

while (condition) {
    // loop body
}

Execution Mechanics

  1. Condition Evaluation: The condition is evaluated first. This expression must be contextually convertible to bool.
  2. Execution: If the condition evaluates to true, the statements within the loop body are executed sequentially.
  3. Iteration: After the loop body completes, control flow jumps back to the condition evaluation.
  4. Termination: If the condition evaluates to false, the loop terminates immediately. Control flow passes to the first statement following the loop block.

Variable Declaration in Condition

C++ permits the declaration and initialization of a variable directly within the while condition. The loop executes as long as the initialized variable contextually converts to true (e.g., non-zero for integers, non-null for pointers).
while (Type variable_name = expression) {
    // variable_name is in scope here
}
// variable_name is out of scope here
Variables declared this way are scoped strictly to the loop block and are destroyed and recreated on every iteration.

Loop Control Statements

The standard execution flow of a while loop can be altered using jump statements:
  • break: Immediately terminates the innermost enclosing while loop. Control flow jumps to the statement immediately following the loop body, bypassing any remaining condition checks.
  • continue: Interrupts the current iteration. Control flow jumps directly to the end of the loop body, skipping any remaining statements, and forces an immediate re-evaluation of the while condition.

Infinite Loops

If the condition expression never evaluates to false and no break statement is encountered, the loop becomes an infinite loop. The standard idiom for an intentional infinite loop in C++ is:
while (true) {
    // executes indefinitely unless interrupted by a jump statement or program termination
}
Master C++ with Deep Grasping Methodology!Learn More