CKTIS / C++
for — classic and range-based loops
The for keyword creates either a classic loop with initialization, a condition, and an update, or a range-based loop over elements. Choose the form according to whether you need explicit index control or access to successive elements.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
for (init-statement condition(optional); expression(optional)) statement
for (init-statement(optional) declaration : range-initializer) statement
// init-statement includes its terminating semicolon.The classic loop for (int i = 0; i < 3; ++i) initializes once, tests its condition before each iteration, then executes the body and the update ++i. A false condition ends the loop; the body may never execute. The variable i declared in the header is unavailable after the loop.
continue proceeds to the update and then tests the condition again. break exits the nearest enclosing loop or switch statement. In the classic form, initialization, condition, and update may be omitted while retaining both semicolons. An omitted condition means true: for (;;). Use {} to group body statements.
The range-based loop for (const auto& value : values) visits successive elements of an array or supported range. In the example’s mutable int array values, auto value copies the element, auto& value lets you modify the element in the array, and const auto& value gives access without copying or allowing modification through that reference. In other ranges, what matters is what dereferencing the iterator yields: auto& value cannot bind to an int prvalue, and if it binds to a const int element, it does not let you modify it. An optional initialization statement can precede the element declaration: for (int sum = 0; const auto& value : values).
The example doubles the elements to 2, 4, 6, then computes the sum 12. This entry targets C++23; the supplied document is an evolving working draft, not a frozen C++23 publication. Production runtime support is not attested.
Examples
#include <iostream>
int main() {
int values[] = {1, 2, 3};
for (int i = 0; i < 3; ++i) {
values[i] *= 2;
}
int sum = 0;
for (const auto& value : values) {
sum += value;
}
std::cout << sum << '\n';
}
Result
12
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.