bhylu.com

Advertisements

C++ While, Break and Continue

Make progress toward a stopping condition and understand which loop break actually exits.

How it works

while tests before the body; do-while tests after it and therefore runs once. A useful loop must advance toward a stopping condition or deliberately exit. continue skips the remaining body of the current innermost loop iteration, while break exits only the innermost loop or switch. For a complete nested search, return from a helper or propagate a named result. An input retry loop must also consume or reject bad input and respect end of file.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror loop-control.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · loop-control.cpp

#include <iostream>

int main() {
    int remaining{3};
    while (remaining > 0) {
        std::cout << "Remaining " << remaining << '\n';
        --remaining;
    }
    for (int row = 1; row <= 2; ++row) {
        for (int slot = 1; slot <= 3; ++slot) {
            if (slot == 2) { continue; }
            if (row == 2 && slot == 3) { break; }
            std::cout << row << '-' << slot << '\n';
        }
    }
}

Expected result

Remaining 3
Remaining 2
Remaining 1
1-1
1-3
2-1

The decrement guarantees progress for the countdown. The nested loop skips slot two and stops only the second row when its final slot is reached. A do-while needs a semicolon after its condition. Keep the state transition near the operation that succeeds so an early continue cannot accidentally bypass a required update.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.