UPI Study › Courses › C++ Programming › Free lessons › Lesson 5.6 Free with a free account
break, continue, and Other Flow Controls
C++ Programming · Chapter 5: IterationSection 5.6 · lesson 34 of 84video coming soon
← Nested IterationNext lesson: Avoiding Loop Traps and Debugging →
In this lesson
Interrupting and skipping.
- State what break and continue do, and where control resumes
- See why continue is risky in a while loop
- Escape nested loops with a flag or a function
- Judge when an early exit helps the reader
Transcript
Everything said in the video, section by section (1,437 words). Read along, or search it.
Opening Problem
When a Loop Condition Isn't Enough
A loop's condition is checked in exactly one place, at the top of each round. That's usually a strength. But sometimes the reason to stop only becomes apparent halfway through the work. Search ten thousand records for one entry, and the match is the second one. With only a condition, the loop still examines all ten thousand. You could force the knowledge upward, by having the body set a value that the condition tests. For a simple case, that's often clearest. But as the reasons multiply, the opening line starts listing everything that might interrupt the loop. So C plus plus provides two statements that act from inside the body. Break ends the loop altogether. Continue abandons the rest of the current round, and moves on to the next.
Loop Cycle
Where Break and Continue Land
Here's the loop cycle again, with the two escape routes drawn in. Normally, the body finishes, the update runs, and control goes back to the test. When the test is false, control goes to the statement after the loop. Break starts in the body and leaves the cycle entirely, landing on that same statement after the loop. Continue also starts in the body, but goes straight to the update, and then back to the test as normal. They differ entirely in where they land.
Code Examples
Stopping at Five, Skipping Evens
Here are both in practice. The first loop runs from 1 to 10, but breaks when i reaches 5. It prints 1, 2, 3, 4. It never prints 5, because the break executes before the printing does. The second loop also runs from 1 to 10, but continues whenever i is even. It prints the odd numbers. All ten rounds run, but only five produce output, because continue jumps past the print without ending anything.
Comparison
Break Versus Continue Side by Side
Reading these two side by side settles most confusion. Break ends the whole loop. Continue ends only the current round. After break, control goes to the first statement after the loop, and the condition isn't retested. After continue, it goes to the update, then the condition. So break leaves no rounds to come, while continue leaves all of them. Break's typical use is a search that has found its target. Continue's is rejecting an item that needs no work.
Counted Loop
Continue Jumps to the Update
Continue behaves differently in a condition-driven loop, and the difference matters. First, a counted loop: when i is 3, continue jumps to the update, so the counter still advances. It prints 1, 2, 4, 5, 6, and finishes.
Quick Check
Continue Inside a While Loop
Now the same idea in a while loop. Quick check: when i reaches 3, continue runs. What happens next? Pause, and trace it.
Answer
The Skipped Increment Traps the Loop
A while loop has no update section to jump to. The advancing usually happens at the bottom of the body, which is exactly the part continue skips. So when i reaches 3, continue skips the line that adds 1. And i stays at 3 forever. It prints 1, 2, and then gets stuck. Before writing continue in a condition-driven loop, check that whatever moves the repetition forward happens above it, not below.
Nested Loops
Escape Statements Reach One Loop
When loops are nested, both statements apply to the nearest enclosing loop, and nothing further out. Here, the outer loop runs three rows. The inner loop runs three columns, but breaks when the column reaches 2. Every row prints 1, and then the message. The break fires on every one of the three passes, and the outer loop completes all three regardless. This is the single most common surprise with these statements. An escape statement reaches exactly one loop outward, never two. There's no form that names a level.
Flag Approach
Leaving Nested Loops With a Bool
So leaving a pair of nested loops from the inner one needs a deliberate arrangement. The first is a flag. Set a bool when the inner loop decides to stop, break out of the inner loop, and have the outer loop's condition test that flag. At row 2, column 2, the inner loop sets done and breaks. It visits 1,1, 1,2, 1,3, then 2,1, and stops. It works, and it's easy to read for two levels. It's also slightly clumsy: the reason for stopping is recorded in one place and acted on in two. A third level makes it worse.
Function Approach
Return Escapes Every Enclosing Loop
The alternative is to move the loops into a function of their own. Since return leaves the entire function, it escapes every enclosing loop in one step. No flag, and no extra condition. This function searches from 1 up to a limit, and returns the first multiple of 7. If nothing matches, it returns minus 1. Up to 20, it returns 7. Up to 5, it returns minus 1. This is usually the better answer. Loops that need an unusual exit are often doing one identifiable job: searching, validating, locating. Giving that job a name makes the surrounding code read better too.
Reach Ranking
How Far Each Exit Travels
A return inside a loop doesn't merely end the loop. It ends the function containing it, immediately, wherever in the nesting it sits. Ordered by reach: continue leaves the current round, and stays inside the loop. Break leaves exactly one loop. Return leaves the whole function, crossing every enclosing loop. And goto leaves whatever lies between here and its label. Spot return while reading. A break tells a reader the code below the loop is about to run. A return tells them the opposite.
Goto Statement
A Direct Jump to a Label
Goto transfers control directly to a labeled statement elsewhere in the same function. It's part of C plus plus, it compiles without complaint, and it solves the nested-loop escape in one line. Here, at row 2, column 2, goto finished jumps clear of both loops, to the label, which prints a message. So it works. The argument against it isn't that it fails. It's that it destroys a property every other control statement preserves.
Goto Debate
Dijkstra and the Case Against Goto
With loops and conditions, you can look at a block of code and know how control could have arrived there: from the line above, or from the construct that encloses it. With goto, control can arrive at a label from anywhere in the function. Answering, how did we get here, means searching the whole function for jumps to that label. This argument was made forcefully in a 1968 letter by the computer scientist Edsger Dijkstra, published as Go To Statement Considered Harmful. It largely won. Escaping nested loops still has defenders, mostly in C code. In C plus plus, extracting a function gives the same exit, costs nothing, and names the job. Learn to recognize goto, so older code isn't opaque to you. And don't reach for it.
Trade-offs
What an Early Exit Costs Readers
Every early exit is a small trade. It buys directness: the loop stops the moment the reason appears. And it spends something: a reader can no longer tell how a loop finishes from its first line. One exit near the top of the body, for a clearly named reason, usually reads well. Several exits at different depths, each for a different reason, usually don't. Continue as a guard, rejecting items that need no work, reads well. Continue buried after thirty lines of work doesn't. The useful question isn't how many exits there are. It's whether a reader can still answer, quickly, under what circumstances does this loop finish.
Practical Test
Deciding Whether to Add an Exit
Here's a practical test before adding an exit. If the condition could express the reason without becoming awkward, prefer the condition. It keeps the summary line honest. If it couldn't, or if doing so means tracking extra values just to feed the condition, the early exit is clearer. And if a loop is accumulating exits, it's probably doing more than one job, and would be better split. In one sentence: continue ends a round, break ends a loop, return ends the function, and goto ends the reader's ability to follow the code.
Key Terms
Early Exits, Labels, and Guards
A few more key terms. An early exit is any departure from a loop or function before its normal end. Function extraction means moving code into a function of its own, so that return can leave several loops at once. A label is a name marking a statement, so a jump can target it. And a guard is an early exit near the top of a body, rejecting cases the rest shouldn't handle.
Summary
Recap and a Closing Puzzle
To summarize. Break ends the enclosing loop, and continue ends only the current round. In a condition-driven loop, make sure the advance happens above any continue. Both statements reach exactly one loop outward. To leave nested loops, a flag works, but extracting a function and returning is usually better. Avoid goto, and keep exits few and visible. Here's something to think about. A loop written to run 10 rounds prints only 1, 2, 3, 4. Which two statements could explain it, and what would reveal the difference?
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About break, continue, and Other Flow Controls
What do break and continue do in a C++ loop, and where does control go next?
Why can continue cause an infinite loop in a while loop?
How do you break out of nested loops in C++?
When is an early exit like break or continue good style?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →