3

This isn't a specific problem that I actually am trying to implement, but it ocurred to me that I do not know how to do this, so I will give a simple example to illustrate:

Suppose we have a while loop containing a switch statement, for instance:

while(some_cond){
    switch(some_var){
        case 1:
            foo();
            break;
        case 2:
            bar();
            break;
    }
}

what would we do if we wanted to break out of the while loop in case 1, say?

We can't do break; break;, since the second will never happen.

We also can't do break *un*conditionally in the while loop, since this would happen in any case.

Do we have no choice but to if (some_var == 1) break; in the while loop, or else append && !flag) to the while condition, and set flag = 1?

OJFord
  • 10,522
  • 8
  • 64
  • 98

3 Answers3

3

Various options, in approximate order of tastefulness:

  • Move the loop into a separate function. Use return to stop looping.
  • Replace while(1) with while(looping) and set to false to stop looping. Use continue if you need to skip the rest of the current iteration.
  • Use goto to jump past the end of the loop. How bad can it be?
  • Surround the loop with a try block, and throw something to stop looping.
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

You can use goto (don't go too wild with goto though).

while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

Have your while use a variable modified within your loop.

bool shoulEnterLoop = true;
while(shoulEnterLoop ){
  switch(some_var){
    case 1:
      if ( !foo() )
        shoulEnterLoop = false;
      break;
    case 2:
      bar();
      break;
  }
}
Vaillancourt
  • 1,380
  • 1
  • 11
  • 42