Lecture 16
12
Leaving a loop body prematurely
•
–while or for (   …   ) {
–   …
–   if ( … )
–      continue;
–   if ( … )
–      break;
–   if ( … )
–      return;
–   …
–   last in loop;  
–}
–next statement;
•Sometimes makes for easy reading,                avoids many else statements.
•Sometimes confusing - can’t trace flow without reading loop body.
return from method
redo loop from top (do test)
leave loop
see JOI/examples/BreakandContinueDemo.java
Not handing out the code for the demo program.

Whether or not using these early returns is a good idea is an “it depends” question. The two bullets summarize the pros and cons.

Early loop exits were explicitly forbidden in Pascal. Early loop exits make mathematical analyses of programs harder.