1

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;
    }
}
Demir
  • 13
  • 5

3 Answers3

5

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:
  // ...
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • Or perhaps just `while (!breakWhile)` ? (after moving its declaration out of the loop, of course) – madreflection Jan 02 '21 at 19:07
  • or that.. I was trying to keep as close to the original structure since I figured the OP is looking for a general approach to breaking out of nested loops, or scopes – Mike Dinescu Jan 02 '21 at 19:09
1

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);
Neil W
  • 7,670
  • 3
  • 28
  • 41
0
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){ }

Michael Gabbay
  • 413
  • 1
  • 4
  • 20