By setting a flag during the body of the loop, and then checking that flag as part of the loop condition. |
But what about the rest of the code in the body of the loop? And it will complicate the loop end condition, especially if there are multiple reasons (multiple places) to exit the loop.
Personally, I prefer that, as it makes the flow of logic through the code more straightforward
|
Not really, because you need extra logic not to do the code in the rest of the body of the loop - as well as extra in the loop condition. It is very simple and logical to use a break.
Your idea is a recipe for complication.
Of course the other way is to return out of the function, but that might not always be convenient - you just want to exit the loop, do something else, then return.
Consider this psuedo code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
while(end-cond1 || (end-cond2 && end-cond3 ) ) {
if (cond1) {
//some code
continue;
}
else if (cond2) {
//found the answer
//do some normal code
return some value
}
else if (err-cond1) {
//some code
break;
}
else if (err-cond2) {
//some code
break;
}
else { //some other error
//some code
break;
}
}
|
So in that code there are 3 normal end conditions for the loop, and 5 other conditions. Imagine if was even worse with even more else if's. And you can't use a switch because the else if clause don't involve integers. Switches normally have breaks after each case clause.
How would you propose to do it without break statements? With 8 end conditions plus more logic to not do the code in the rest of the body of the loop?
Of course the other aspect of this is to use exceptions to process errors - but what if they aren't errors? It is the same as a list of else if clauses doing the same as a switch for the reasons I mentioned above. The breaks are needed for the same reason they are needed in a switch.
I look forward to your answer.