Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case to break an outer loop? [duplicate]

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?

like image 871
OJFord Avatar asked Jan 24 '26 13:01

OJFord


2 Answers

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.
like image 145
Mike Seymour Avatar answered Jan 26 '26 07:01

Mike Seymour


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

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

   }
}
exit_loop: ;
like image 21
herohuyongtao Avatar answered Jan 26 '26 08:01

herohuyongtao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!