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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Nested Loops and Common Loop Errors →← The do-while LoopNext lesson: Nested Loops and Common Loop Errors →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
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 Interrupting Normal Flow: break, continue, and goto
What is the difference between break and continue in C?
Does break inside a switch exit the surrounding loop?
Why can continue cause an infinite loop in a while loop?
When is it acceptable to use goto in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →