break nested loop

Aug 31, 2008 at 10:37am
Dear all

i have a little problem in my programing i have a nested for loop and in the final loop i have to get out of all the nested loop( by the way i tried beark statemnet but it gets me out of the neartest for loop) is there another way to do it without using the statement goto ( because in another forums they suggest to use goto , but goto is not good in programing in c++), i wrote a simple code to explain what i want to know,

for ( int i =0 ; i < 20; i++)
{
//...
//... some statement in my code
//...

for (int j =0; j<10; j++)
{
//...
//... some statement in my code
//...
if ( x==5)
break;
}
}

so in the above example i have a variable x and if the value of x equal to 5 i i have to stop the nested two loops.

by the way i came her because i heard that i can find help in this forums ,because i tried another forums before and as i wrote above they only tell me to use the goto statement

and i will be very thankfull for any help or tips to solve my problem

with best wishes

Aug 31, 2008 at 12:07pm
There are many ways to do this. One possibility is the following:

for ( int i =0 ; i < 20; i++)
{
//...
//... some statement in my code
//...

for (int j =0; j<10; j++)
{
//...
//... some statement in my code
//...
if ( x==5)
break;
}
if(j != 10){
break;
}
}
Aug 31, 2008 at 12:15pm
That's one use of the goto command.
http://www.cplusplus.com/doc/tutorial/control.html

jmc's method works also but you have to declare the int j; before the beginning of the nested for-loop (not in the for-loop), or else it will be uknown outside, where you check for it's value.
Aug 31, 2008 at 12:52pm
Dear JMC

i just want to thank you for your good idea, it is helpfull

with best wishes

Topic archived. No new replies allowed.