hd0502-scaled

To break out from a deeply Nested loop

In this tip I am explaining different ways to break out of a very deeply nested loop. Also the pros and cons of each method. Also show the use of anonymous method for implementing this functionality.

Use of anonymous method to break out from a deeply nested loop

Sometime we may face a situation when we need to break from a deeply nested loop. We have many options to achieve this thing. Few of them are described below:

- Use of goto:

for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{

if( j == 25)
goto Foo;
}
}

Foo:

But goto is not a preferable keyword among the developers.

– Set the loop variables value to the max integer value so that the checking condition will false.

for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
if (j == 25)
{

i = INT_MAX;

break;
}
}
}

But if your loop is a very deeply nested loop then you have to set every loop variables value to maximum value if you want to exit from all the loops.

– Use of an extra boolean variable in the loop checking condition.

bool exitLoop = false;
for (int i = 0; i < 100 && !exitLoop; ++i)
{
for (int j = 0; j < 100; ++j)
{
if (j == 25)
{
exitLoop = true;
break;
}
}

}

In this condition you have to check the boolean value in every loop. It may be resulted in some extra work if you have a very deeply nested loop.

– Use of exception handling

try

{
for ( int i = 0; i < 100; ++i )
{
for ( int j = 0; j < 100; ++j )
{
if (j == 25)
{
throw new Exception()
}
}
}
}
catch ( Exception e ) {}

But throwing and handling exception is an extra overhead.

– So finally we have a very efficient and advanced way of doing this thing. And that is the use of anonymous method.

//Declare the anonymous method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
if( y == 25)
{
return; // exits anonymous method
}
}
}
};
work(); // execute anonymous method.
2560 1440 Burnignorance | Where Minds Meet And Sparks Fly!