How can I do this cleanly without gotos?
loop:
if(condition1){
something();
} else if (condition2) {
somethingDifferent();
} else {
mostOfTheWork();
goto loop;
}
I'd prefer not to use breaks as well. Furthermore, it is expected to loop several (adv 40) times before doing something else, so the mostOfTheWork part would most likely be as high up as possible, even if just for readability. Thanks in advance.
EDIT: This was posted under the misconception that the compiler optimizer worked poorly with breaks, which, while generally stupid to begin with, I have proven incorrect to myself through experimentation (of performance). On the other hand, thank you for your answers; they have been interesting reads on varying styles.
Clearly, you will break out of the loop if either condition fires.
while ((!condition1) && (!condition2)) {
MostOfTheWork();
}
if (condition1) {
something();
} else if (condition2) {
somethingDifferent();
}
So, loop while neither condition has fired, then see which one got you.
Now, someone will scream that I evaluated the conditions more than I needed to. For their benefit, a modified version:
{
bool t1, t2;
while ((!(t1 = condition1)) && (!(t2 =condition2))) {
MostOfTheWork();
}
if (t1) {
something();
} else if (t2) {
somethingDifferent();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With