hi
If a switch-case is inside a while-loop how to get out of while-loop without using if- conditional statement(using break inside switch gets only out of switch).
Printable View
hi
If a switch-case is inside a while-loop how to get out of while-loop without using if- conditional statement(using break inside switch gets only out of switch).
use additional flag in the while condition
Throwing an exception would certainly get you out of everything until you reach a catch statement, but that's probably not what you want.
Goto would work, but in 99.999% of the time, it's very bad to use, especially for beginners.
Why don't you want to use an if statement after the switch to break out of the while loop?
If there are n-cases in a switch,at each time in a loop ,one of the cases is executed,after all the n-cases are executed,if the default-case takes the control out of the while-loop ,the code would be cleaner than using a if statement after the switch.Quote:
Why don't you want to use an if statement after the switch to break out of the while loop?
Good idea.Quote:
use additional flag in the while condition
Or put the whole while-loop in a seperate function and simply return from the particular place inside the switch.
Well, I would say that the only common case that goto seems reasonable to use is when you want to break from more than one "block" of code, since there is no such think as break2 etc etc. But I won't say anything, I don't use goto my self either....
That is certainly a sort of valid use of goto, but I would thinkt that setting a flag to break the loop would work just as well, and make it at least as obvious what is going on.
If there is some processing outside of the switch, perhaps a "breakflag" is most appropriate, e.g.
In some ways, a goto may be more obvious, since you at least see the label.Code:while(true)
{
... some code
switch(x)
{
case ...:
...
if (y) breakflag = true;
else {
...
....
}
break;
... // more cases and default
}
if (breakflag)
break; // Ends while-loop.
... More code here.
}
--
Mats
--
Mats
which can be replaced with while(!breakflag) which is exactly what I would prefer, but my point was that if you have a fair bit of code AFTER the end of the switch statement, the if(breakflag) break will break the while-loop before that code, rather than wrapping the whole lot of code in a if(!breakflag).
--
Mats