`while` — C++ Keyword

`while` — C++ Keyword

The while keyword in C++: repeatedly executes a body as long as a condition is true.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

while

Repeatedly executes a statement as long as the controlling condition evaluates to true. The condition is checked before each iteration, so the body may execute zero times.

Syntax

while (condition) statement

Example

#include <print>

int main() {
    int n = 1;

    while (n <= 5) {
        std::print("{} ", n);
        ++n;
    }
    // Output: 1 2 3 4 5

    std::println();

    // Reading until a sentinel
    int sum = 0;
    int val = 0;
    // while (std::cin >> val && val != 0) { sum += val; }
    (void)sum;
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}