If I use a break
statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will
One way is to put all the nested loops into a function and return from the inner most loop incase of a need to break out of all loops.
function()
{
for(int i=0; i<1000; i++)
{
for(int j=0; j<1000;j++)
{
if (condition)
return;
}
}
}
You'll need a boolean variable, if you want it readable:
bool broke = false;
for(int i = 0; i < 1000; i++) {
for(int j = 0; j < 1000; i++) {
if (condition) {
broke = true;
break;
}
}
if (broke)
break;
}
If you want it less readable you can join the boolean evaluation:
bool broke = false;
for(int i = 0; i < 1000 && !broke; i++) {
for(int j = 0; j < 1000; i++) {
if (condition) {
broke = true;
break;
}
}
}
As an ultimate way you can invalidate the initial loop:
for(int i = 0; i < size; i++) {
for(int j = 0; j < 1000; i++) {
if (condition) {
i = size;
break;
}
}
}
int i = 0, j= 0;
for(i;i< 1000; i++){
for(j; j< 1000; j++){
if(condition){
i = j = 1001;
break;
}
}
}
Will break both the loops.
bool stop = false;
for (int i = 0; (i < 1000) && !stop; i++)
{
for (int j = 0; (j < 1000) && !stop; j++)
{
if (condition)
stop = true;
}
}
Caution: This answer shows a truly obscure construction.
If you are using GCC, check out this library.
Like in PHP, break
can accept the number of nested loops you want to exit.
You can write something like this:
for(int i = 0; i < 1000; i++) {
for(int j = 0; j < 1000; j++) {
if(condition) {
// break two nested enclosing loops
break(2);
}
}
}
for(int i = 0; i < 1000; i++) {
for(int j = 0; j < 1000; i++) {
if(condition) {
goto end;
}
}
end: