break
The
break statement forces the loop
from which it is called to be exited. If such a loop is contained within
another loop, the containing loop will keep iterating. Given the nested
loops:
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
cout << i << " " << j << " - ";
if(i == j)
break; // breaks only innermost for
}
cout << endl;
}
Whenever the condition:
i == j
is met, the
break statement is called.
As a consequence the inner loop is broken out of, and
cout << endl;
is executed. After that, if the conditional statement:
i < 5
is met, a new iteration of the outer loop takes place,
possibly re-entering the inner loop - if the:
j < 5
condition is met.
Example
#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
cout << i << " " << j << " - ";
if(i == j)
break; // breaks only innermost for
}
cout << endl;
}
cout << endl;
}
Output
0 0 -
1 0 - 1 1 -
2 0 - 2 1 - 2 2 -
3 0 - 3 1 - 3 2 - 3 3 -
4 0 - 4 1 - 4 2 - 4 3 - 4 4 -