break, continue, and Other Flow Controls | C++ Programming

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 →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Break ends the whole loop, and continue ends only the current round. After break, control lands on the first statement after the loop without retesting the condition. After continue, control goes to the update section, if there is one, and then back to the loop test.
Why can continue cause an infinite loop in a while loop?
Continue skips the rest of the body, and a while loop has no update section to jump to. If the increment sits at the bottom of the body, continue skips it, so the counter never advances. For example, if i stays at 3, the loop prints 1, 2 and then gets stuck. Put the advance above any continue.
How do you break out of nested loops in C++?
Use a bool flag that the outer loop tests, or move the loops into a function and return from it. A break leaves only the nearest enclosing loop or switch, so a flag must be set before breaking, and the outer condition must check it. Return exits every enclosing loop at once and is usually cleaner.
When is an early exit like break or continue good style?
An early exit helps when it is rare, visible, and has a clear reason, such as a search that stops once it finds its target. If the loop condition can state the reason without becoming awkward, prefer the condition. Several exits at different depths make it hard for a reader to tell how the loop finishes.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

C++ Programming
3 credits · NCCRS
Enroll →