Table of Contents
The break statement can be used inside loops to terminate the nearest enclosing loop immediately. When break is executed, control is transferred to the first statement following the loop.
This allows a loop to terminate before its controlling condition becomes false, which is useful when a required condition is detected during iteration.
Source Code #
#include <iostream>
int main()
{
for (int number = 1; number <= 10; ++number)
{
if (number == 6)
{
break;
}
std::cout << number << '\n';
}
std::cout << "Loop terminated.\n";
return 0;
}
Output #
1
2
3
4
5
Loop terminated.
Explanation #
- The
forloop is configured to iterate from1through10. - During each iteration, the
ifstatement checks whethernumberis equal to6. - When
numberbecomes6, the condition evaluates totrue. breakimmediately terminates theforloop.- The value
6is therefore not printed becausebreakexecutes before thestd::coutstatement. - Execution continues with the statement following the loop.
breakterminates only the nearest enclosing loop.return 0;terminates the program successfully.