Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rewrite this (cleanly) without gotos?

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.

like image 859
Jared Pochtar Avatar asked Nov 28 '22 11:11

Jared Pochtar


1 Answers

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();
  }
}
like image 58
John R. Strohm Avatar answered Dec 16 '22 03:12

John R. Strohm