bhylu.com

Advertisements

C++ For and Range-based Loops

Use a counted loop for numbered work and a range-based loop for existing collection elements.

How it works

A for loop keeps initialization, condition and update together. Its condition is tested before each iteration, allowing an empty traversal. A range-based for loop expresses a visit to each element without manual index arithmetic. Prefer the range form when positions are irrelevant. Choose a reference loop variable only when you need mutation or want to avoid a copy of a larger element; a copied small int is often simpler and cheap.

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 loops.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 · loops.cpp

#include <iostream>
#include <array>

int main() {
    for (int stop = 1; stop <= 3; ++stop) { std::cout << "Stop " << stop << '\n'; }
    std::array<int, 3> parcels{2, 4, 3};
    int total{0};
    for (int count : parcels) { total += count; }
    std::cout << "Total: " << total << '\n';
}

Expected result

Stop 1
Stop 2
Stop 3
Total: 9

The counted loop deliberately prints one-based display numbers. The range loop visits three stored values and accumulates their small safe total. When indexing a container, valid positions normally use index < size rather than <=. A container can have zero elements, so do not read its front or back without checking non-emptiness.

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.