Let\'s say I have this:
while(a){
while(b){
if(b == 10)
break;
}
}
Question: Will the break statement take m
In your example break statement will take you out of while(b) loop
while(a) {
while(b) {
if(b == 10) {
break;
}
}
// break will take you here.
}
It will break out of the loop that immediately encloses it.
You can however, break to a label:
myLabel:
while(a) {
while(b) {
if(b == 10)
break myLabel;
}
}
I don't generally like to use this pattern because it easily leads to spaghetti code. Use an unlabeled break or a flag to terminate your loop.
A break
statement will take you out of the innermost loop enclosing that break
statement.
In the example the inner while loop.
@Abhishekkumar
Break keyword has it's derived root from C and Assembly, and Break it's sole purpose to passes control out of the compound statement i.e. Loop, Condition, Method or Procedures.
Please refer these...
http://tigcc.ticalc.org/doc/keywords.html#break
http://www.functionx.com/cpp/keywords/break.htm
http://en.wikipedia.org/wiki/Break_statement#Early_exit_from_loops
So, if you want to get out of Two loops at same time then you've to use two Breaks, i.e. one in inner loop and one in outer loop.
But you want to stop both loop at same time then you must have to use exit or return.
You can raise a flag to pass the information to the outer while loop. In this case the information can be stored in a variable breakOuterLoopFlag
and the outer while loop acts according to this information.
See pseudo code below:
int breakOuterLoopFlag = 0;
while(a){
while(b){
if(b == 10) {
breakOuterLoopFlag = 1;
break;
}
}
if(breakOuterLoopFlag == 1) {
break;
}
}