I want to break this while
loop if n
equals 3 but how can I do?
n = 0;
while(true){
switch (n){
case 3:
break;
default:
break;
}
}
I want to break this while
loop if n
equals 3 but how can I do?
n = 0;
while(true){
switch (n){
case 3:
break;
default:
break;
}
}
You can't break out of a nested block. You must use a different conditional control structure.
For example, you can use a boolean in the while loop:
while(true) {
var breakWhile = false;
switch(n) {
case 3:
breakWhile = true;
break;
default:
break;
}
if (breakWhile) {
break;
}
}
This is a fairly contrived example to show how you would do it in a general sense.
In this simple example you can simplify the code to just:
while (n != 3) {
}
But I figured you're interested in a general approach to breaking out of nested structures.
Another, frowned upon practice, would be to use a goto statement. You should generally avoid this but showing here for sake of completeness and because incidentally, getting out of deeply nested loops is one of the few acceptable uses of the goto
statement.
From docs:
The goto statement is also useful to get out of deeply nested loops.
while (true) {
switch(n) {
case 3:
goto outer_scope;
default:
break;
}
}
outer_scope:
// ...
One way is to use a do ... while, instead of a while ... do.
var n = 0;
do {
switch (n)
{
case 3:
break;
default:
break;
}
} while(n != 3);
bool run = true;
n = 0;
while(run){
switch (n){
case 3:
run = false
break;
default:
break;
}
}
or you can use n
n = 0; while(n!=3){ }