- Forward


Breaking Out of Loops
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Recall:
    • There are definite loops and indefinite loops
  • An Observation:
    • Sometimes we want to break out of a loop "early"
A Language Feature
Back SMYC Forward
  • The Statement:
    • Some languages have a break statement that causes control to be transferred to the end of the immediately enclosing loop
  • A Common Recommendation:
    • Use the break statement sparingly (if at all)
An Example
Back SMYC Forward

Print Up To and Including the First Negative Number

javaexamples/programmingpatterns/LoopBreakExample.java (Fragment: break)
 
Problems with the break Statement
Back SMYC Forward
  • Legitimate Confusion:
    • break statements can be hard to see
  • "Nesting" that Causes Confusion (though Shouldn't):
    • break statements are often in if statements in loops
    • break statements are often in nested loops
An Alternative Approach
Back SMYC Forward
  • The Idea:
    • Include the early termination condition in the loop termination condition
  • Why It Works:
    • The loop termination condition can be any boolean expression
An Example
Back SMYC Forward

Print Up To and Including the First Negative Number Revisited

javaexamples/programmingpatterns/LoopBreakExample.java (Fragment: condition)
 
Some Observations
Back SMYC Forward
  • Reading Code that Uses break Statements:
    • Many people use them so you must understand them
  • Writing Code that Changes the Termination Condition:
    • All of the termination conditions are collected in one place
    • Makes it clear that the loop is indefinite (which is "hidden" by the break statement)
    • It is easy to incorporate multiple early termination conditions
    • It is often possible to eliminate the if statement (e.g., replace if (data[i] < 0) done = true; with done = (data[i] < 0);)
There's Always More to Learn
Back -