In one of my programs, I have code like this:
Code:
void f()
{
//...
for (/* blah blah*/)
{
switch (/* blah blah */) {
case X:
//do stuff...
case Y:
//do stuff...
//...
}
}
//...
}
In some cases inside the switch statement, I want the program to get out of the for loop and continue in the function. What's a good way to do this?
I tried this:
Code:
void f()
{
//...
bool quit = false;
for (/* blah blah*/)
{
if (quit) {
//some code...
break;
}
switch (/* blah blah */) {
case X:
//do stuff...
quit = true;
break;
case Y:
//do stuff...
//...
}
}
//...
}
But if case X is found at the last iteration of the loop, then the "some code..." part inside the if statement won't be reached because the program will break out of the loop and won't check wether quit == true.
Then I did this:
Code:
void f()
{
//...
class Stop_Loop {};
for (/* blah blah*/)
{
switch (/* blah blah */) {
case X:
//do stuff...
throw Stop_Loop();
case Y:
//do stuff...
//...
}
}
catch (Stop_Loop) {};
//...
}
And it works fine. But I want to know if there's a better way than using exceptions to do this. Maybe it's really easy to do but I haven't come up with another way yet.