I have the following code:
int x = 100; //Or some other value
while(x > 0) {
for(int i = 5; i > 0; i++) {
x = x-2;
if(x == 0)
break;
}
}
However, this will only break the for loop. How can I have it so that it breaks both the for and the while loops?
Cheers!
You can use a labeled break, which redirects the execution to after the block marked by the label:
OUTER:
while(x > 0) {
for(int i = 5; i > 0; i++) {
x = x-2;
if(x == 0)
break OUTER;
}
}
Although in that specific case, a simple break
would work because if x == 0
the while will exit too.
bool done=false;
while(!done && x > 0) {
for(int i = 5;!done && i > 0 ; i++) {
x = x-2;
if(x == 0){
done=true;
break ;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With