Interrupting Normal Flow: break, continue, and goto, Explained

UPI Study › Courses › Programming in C › Free lessons › Lesson 5.5 Free with a free account

Interrupting Normal Flow: break, continue, and goto

Programming in C · Chapter 5: Loop Constructs, Control Statements, and Error DiagnosisSection 5.5 · lesson 30 of 788 min · free with a free account

← The do-while LoopNext lesson: Nested Loops and Common Loop Errors →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Leaving loops early, skipping passes and jumping with goto in C.

  • Use break to leave the nearest loop or switch
  • Use continue to skip the rest of one pass
  • Explain why continue can cause an infinite while loop
  • Describe the accepted uses of goto and why it is discouraged

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,273 words). Read along, or search it.

Opening Analogy

Changing Plans in the Middle

You're in the middle of a movie when the fire alarm rings. You don't finish the film first. You get up, right now. Loops have the same problem. Usually every pass runs from start to finish. But sometimes you find what you came for, or spot one bad item, and need to change plans on the spot. C gives you three tools for that. Break leaves the loop. Continue skips to the next pass. And goto jumps to a label. The first two are everyday helpers. The third is a tool to know about, and almost never pick up.

break

The Loop's Emergency Exit

Break, followed by a semicolon, means: stop this loop immediately. The rest of the body is skipped, no more tests are made, and the program carries on after the loop. Think of it as the loop's emergency exit. Here's a game at the Starlight Arcade. Each round scores the round number times itself. A score over twenty wins the jackpot, and ends the game. The loop may run up to ten rounds. It won't need them all. Build and run it. Rounds one to four score twenty or less, so the if is false. Round five scores twenty-five. The if is true, and break jumps out. Rounds six to ten never happen. And look at the last line: round is five, not eleven. Break left before the update, round plus plus, could run again. That's also why round is declared before the loop. A variable made in the header would be gone by then.

break in a switch

Leaving the Switch, Not the Loop

Break leaves only the nearest loop or switch around it, and nothing further out. In four point six, you used break to end each case of a switch. Put that switch inside a loop, and the break ends the case, not the loop. Here, turn two picks Quit. Build and run it. Quit picked. But end of pass two still prints, and turn three still happens. The break only left the switch. To stop the loop from in there, you need something else: a flag that the loop's condition checks, or a return from the whole function, which comes in six point one. Or the goto you're about to meet.

Quick Check

A Break That Never Fires

Quick check. This loop runs n from one to six, and breaks out as soon as n times n is over forty. What value of n does it print? Pause and predict. It prints n equals seven. The biggest square it reaches is six times six, thirty-six, which isn't over forty. So break never runs. The loop ends the normal way: n plus plus makes n seven, and seven fails the test, n at most six. Six would be right only if break had fired on the last pass. A break that never runs changes nothing.

continue

Skipping the Broken Machine

Sometimes one item is bad, but the rest are fine. A school bus doesn't cancel the trip because one house is empty. It drives past, and goes on to the next. That's continue. It ends the current pass only. In a for loop, it jumps to the update, and the loop carries on. Sam, who tests the arcade's programs, is checking five machines. Machine three is broken, so the program tells him, and skips it. Build and run it. Machines one and two are tested. Three is skipped. Four and five are tested. Working machines: four. Machine three never reached the line that adds one to working. With break in place of continue, the check would have stopped at machine three, and four and five would never be tested.

Common Mistake

Continue Skips a while Loop's Update

Be careful with continue in a while loop. In a for loop, the update sits in the header, so continue still reaches it. In a while loop, the update is inside the body, and continue can jump right over it. Here, machine plus plus is at the bottom. Build and run it. Machines one and two, and then machine three, over and over. Continue skips machine plus plus, so machine stays at three, and the condition stays true forever. Control C stops it. The cure: put the update above the continue, or use a for loop.

Quick Check

Skipping Multiples of Three

Quick check. Here k runs from one to six. When k divides evenly by three, continue skips the rest of the pass. What is count at the end? Pause and predict. It prints count equals four. Three and six divide evenly by three, so those two passes skip count plus plus. The other four passes count. Two would be the answer for break, which would stop the whole loop at three. Continue only skips one pass, and carries on.

goto

Labels and Unconditional Jumps

The third tool is different. A label is a name followed by a colon, put in front of a line. Goto, then that name, jumps straight to it, from anywhere in the same function. No condition, no loop rules. Just a jump. You could even build a loop by hand: a label at the top, and a goto back up while a condition holds. It works, but you'd have to read every line to see it's a loop, while a for loop says so in one line. That's the first reason goto is discouraged: it hides the shape of the program.

Accepted Use

Leaving Two Loops at Once

Here's where goto earns its keep. The arcade has four rows of five seats, numbered one to twenty, row by row. A loop inside a loop searches for seat eight. Those get their own lesson, five point six. For now: the outer loop picks a row, and the inner loop walks its seats. When seat eight turns up, this version uses a plain break. Build and run it. Found seat eight. But the outer loop carries on: rows three and four are searched for nothing. Then it even claims that seat eight doesn't exist. Break climbed out one level, not two. Now replace the break with goto finished, and put the label, finished, just before the last printf. Build and run it again. Done with row one, found seat eight, search over. One jump left both loops, and skipped the does-not-exist line too. That's the case experienced C programmers accept: leaving several levels at once. A second accepted use is one cleanup spot at the end of a function, when several steps can fail. You'll see it once programs open files, in nine point five, and allocate memory, in eleven point two.

History

Dijkstra and Spaghetti Code

So why is goto discouraged? A jump down and out is easy to follow. The trouble starts when jumps go in every direction. Then the reader has to trace arrows across the page to know what runs when. Programmers call that spaghetti code, because the paths twist together like noodles. In 1968, the computer scientist Edsger Dijkstra published a short letter, titled Go To Statement Considered Harmful. It helped push languages toward loops and functions. C still has goto, but good C code uses it rarely. Reach for for, while, break and continue first. And if you do use goto, jump forward, to a label near the end of the function. Never jump backward to build a loop by hand. Priya, who writes the arcade's programs, once wrote a seat finder with four labels jumping up and down. Sam couldn't test it. He couldn't even tell which line ran after which.

Key Takeaways

Jump Statements in Review

To sum up. Break leaves the nearest loop or switch at once, and nothing further out. Continue ends only the current pass. In a while loop, make sure it can't skip the update. Goto jumps to a label in the same function. Its one fair use in loops is leaving several levels at once. And keep every jump forward, and rare. Jump rarely, and forward only.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

Programming in C 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 Interrupting Normal Flow: break, continue, and goto

What is the difference between break and continue in C?
break ends the nearest loop or switch immediately, while continue ends only the current pass and moves on to the next one. If a loop over machines 1 to 5 runs continue for broken machine 3, machines 4 and 5 are still tested. With break in its place, the loop would stop at machine 3, and machines 4 and 5 would never be tested.
Does break inside a switch exit the surrounding loop?
No. break leaves only the nearest enclosing loop or switch, so a break inside a switch ends the switch, and the loop keeps going. A menu loop whose Quit case uses break will still run its next pass. To stop the loop from inside the switch, use a flag that the loop's condition checks, return from the function, or jump forward with goto.
Why can continue cause an infinite loop in a while loop?
In a while loop the update usually sits at the bottom of the body, so continue can jump right over it. If machine++ comes after a continue that fires for machine 3, machine stays at 3 and the condition never becomes false. In a for loop the update is in the header, so continue still reaches it. Put the update above the continue, or use a for loop.
When is it acceptable to use goto in C?
goto is generally accepted for leaving several nested loops at once and for jumping to one cleanup section at the end of a function when several steps can fail. A plain break leaves only one loop level. Edsger Dijkstra's 1968 letter Go To Statement Considered Harmful criticized jumps that tangle into spaghetti code. Keep goto rare, and jump forward to a label in the same function.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →