# c++ 如果達到結束條件，是否可以在C ++之前退出？

``````for (int i=0; i<maxi; ++i) {
bool leaveLoop = false;
for (int j=0; j<maxj; ++j) {
if (i == 4 && j == 3) {
leaveLoop = true;
break; // leave the inner loop
}
}
if (leaveLoop) {
break; // leave the outside loop
}
}``````

``````try {
for (int i=0; i<maxi; ++i) {
for (int j=0; j<maxj; ++j) {
if (i == 4 && j == 3) {
throw leave_loop();
}
}
}
} catch (leave_loop const&) {
}``````

``````int j = 0;
for (int i=0; i<maxi && !(i==4 && j==3); ++i) {
for (j=0; j<maxj && !(i==4 && j==3); ++j) {
// inner loop
}
}``````

`goto`

``````for (int i=0; i<maxi; ++i) {
for (int j=0; j<maxj; ++j) {
if (i==4 && j==3) {
goto leave_loop;
}
}
}
leave_loop:``````

c++ loops label nested-loops

``````for (int i = 0; i < maxi; ++i)
for (int j = 0; j < maxj; ++j)
// But if i == 4 < maxi AND j == 3 < maxj,
// then jump out of the two nested loops.``````

``````bool done = false;

for (int i = 0; i < maxi && !done; ++i)
for (int j = 0; j < maxj && !done; ++j)
if (i == 4 && i < maxi && j == 3 && j < maxj )
done = true;
else {
}``````

``````for (int i = 0; i < maxi; ++i)
{
int j = 0;
for (j = 0; j < maxj; ++j)
{
if (i == 4 && j == 3) // i < maxi and j < maxj otherwise we would not be here
break; // exit inner loop
}
if (i == 4 && j == 3) // i < maxi and j < maxj otherwise we would not be here
break; // exit outer loop
}``````

Java的：

``````iterate_rows:
for (int i = 0; i < maxi; ++i)
{
for (int j = 0; j < maxj; ++j)
{
if (i == 4 < maxi && j == 3 < maxj)
break iterate_rows;
else
continue iterate_rows;
}
}``````

C ++：

``````//iterate_rows:
for (int i = 0; i < maxi; ++i)
{
for (int j = 0; j < maxj; ++j)
{
if (i == 4 < maxi && j == 3 < maxj)
goto break_iterate_rows;
else
goto continue_iterate_rows;
}

continue_iterate_rows:;
}
break_iterate_rows:;``````

goto break_iterate_rows只是break iterate_rows可見版本

PS

``````int i = 0;
int j = 0;
while (i < SIZE && a[i][j] != target) { // still in array but not at target
if (SIZE <= ++j) {                  // fallen off the end of a row
j = 0;
++i;
}
}``````

``````    if (target < a[i][j] || SIZE <= ++j) { // can't be in row or fallen off end
...``````

### Tags

c++   loops   label   nested-loops