In my opinion, this version of the code most clearly conveys the program flow to the offspring and most easily extends. Yes, I use break . I canβt think of any real reason not to do this.
while(true) { if (condition1) { something(); break; } if (condition2) { somethingDifferent(); break; } mostOfTheWork(); }
If you really don't want to use break , you can use goto to exit the loop or use return to execute the function (if this loop is part of a larger function you will have to refactor it).
while(true) { if (condition1) { something(); goto exit; } if (condition2) { somethingDifferent(); goto exit; } mostOfTheWork(); } exit:
or
while(true) { if (condition1) { something(); return; } if (condition2) { somethingDifferent(); return; } mostOfTheWork(); }
And if you refuse to use any flow control other than if and while, how about this:
bool ok = true; while(ok) { if (condition1) { something(); ok = false; } if (ok && condition2) { somethingDifferent(); ok = false; } if (ok) { mostOfTheWork(); } }
Also, see my canonical answer to this question (and vote for it!)
source share