CKTIS / C++
break — terminate a loop or switch
The break; statement terminates the nearest enclosing loop or switch statement. Execution continues after the terminated statement, rather than proceeding to the next loop iteration.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
break;The break; statement unconditionally terminates the nearest enclosing loop (for, range-based for, while, or do) or switch statement. Control passes to the statement following that construct, if any. The semicolon is required; break takes neither a value nor a label.
In nested constructs, it terminates only the nearest one: a break inside a switch within a loop exits the switch, not the loop. An if or an ordinary {} block is not itself a target for break. In C++23, using it without an enclosing loop or switch is ill-formed.
Unlike continue, break terminates the entire loop instead of proceeding to its next iteration. In a switch, it prevents fallthrough to subsequent case labels. It does not exit the function as return does. When scopes are exited, objects with automatic storage duration constructed in those scopes are destroyed in reverse construction order.
In the example, sum starts at 0. Adding 1, 2, and 3 in order gives sum the successive values 1, 3, and 6. When n == 4, break skips sum += n; and terminates the loop, so the program prints 6 followed by a newline. This entry targets C++23; the supplied site hosts an evolving working draft, not a frozen C++23 edition.
Examples
#include <iostream>
int main() {
int sum = 0;
for (int n = 1; n <= 5; ++n) {
if (n == 4) {
break;
}
sum += n;
}
std::cout << sum << '\n';
}
Result
6
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.