UPI Study › Courses › Programming in C › Free lessons › Lesson 4.6 Free with a free account
The switch Statement
Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.6 · lesson 24 of 786 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: Workshop: Menu-Driven Programs and Grade Calculators →← Multi-Tier Decision Chains: else-if and Nested ConditionsNext lesson: Workshop: Menu-Driven Programs and Grade Calculators →
In this lesson
Jumping straight to the matching case with C's switch statement.
- Write a switch with case labels, break and default
- Explain fall-through and when it is useful
- Identify selector and label types that switch rejects
- Choose between a switch and an else-if chain
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 (870 words). Read along, or search it.
Opening Problem
A Ride Menu Asks One Question
Picture the ride menu at the Starlight Arcade. Press one for Bumper Cars, two for the Comet Coaster, three for the Ferris Wheel. An else-if chain would work. But it asks the same question again and again: is the choice one? Is it two? Is it three? C has a tool built for exactly this job. It looks at the number once, and jumps straight to the right place.
Anatomy
Selector, Case Labels, Break and Default
A switch statement looks at one value, called the selector, and jumps to the case label that matches it. Think of a building with numbered doors. You don't try door one, then door two. You read your ticket, and walk straight to the right door. The selector goes in parentheses after switch. It must be a whole-number type, like int, or char, since a character is a small whole number underneath. Each case label names one constant value, followed by a colon. And break jumps out of the switch. Default is the anything-else door, like the final else of a chain. It's optional, but without it, a menu stays silent when a player presses nine. Run it with choice two. C jumps to case two, prints Comet Coaster, and break ends the switch.
Fall-Through
A Missing Break Keeps Running Down
Here's the surprise that catches every beginner. A case label is only a landing spot. C jumps to it, then keeps running downward, through the next labels, until it meets a break or the closing brace. That sliding is called fall-through. Sam deleted one break to see what happens. With choice one, he wanted only Bumper Cars. Build with wall and W extra, and run. No warning at all, and Comet Coaster printed too. In GCC, W extra turns on the fall-through warning, but clang needs it by name. Add W implicit fallthrough, and clang points at case two. Its notes offer two fixes: insert a break, or mark the fall-through as intended. A missing break compiles and runs, so never ignore this warning.
Intentional Fall-Through
Tiered Bonuses That Add Up
Fall-through can also be useful. Gold gets the gold, silver, and bronze bonuses. Silver gets silver and bronze. Run it for tier G: ten, plus five, plus one. Sixteen bonus tokens. The comments say fall through, so a reader knows it's meant, and GCC reads those comments too. Clang's warning ignores comments. With that flag on, use the attribute from its note.
Quick Check
A Snack Menu Missing Breaks
Quick check. A new snack menu, with some breaks left out. The choice is two. What does it print? Pause and predict. Build and run it. It prints soda, then popcorn. C jumps straight to case two, so the pretzel line above is never touched. Case two has no break, so it falls into case three, which prints popcorn and then breaks. Default is never reached.
Limits
No Strings, Decimals or Ranges
Case labels are matched by exact equality, against a whole-number constant. That rules out a few things beginners try. First, text. A string in C isn't a whole number, so switch can't take one. Clang refuses: statement requires expression of integer type. Second, decimals. A double selector is refused with the same message. Third, ranges and conditions. A label like case score at least ninety is rejected too: expression is not an integer constant expression. Standard C has no range label at all. GCC and clang offer one as their own extension, which other compilers may reject. For those jobs, use an else-if chain.
Useful Trick
Dividing a Score by Ten
There's a neat trick, though. Divide, to turn a range into one number. Eighty-seven divided by ten is eight, in whole-number arithmetic. So case eight runs: grade B. And look at case ten and case nine, stacked with no code between them. They share one block. That's fall-through used as a feature. The compiler doesn't warn, because there's no code to fall from.
Choosing a Tool
Switch Versus an else-if Chain
So which tool? Neither is better. Pick the one that reads like the question you're asking. Exact whole numbers or characters, like menu keys or letter grades, suit a switch. Ranges, decimals, text, or tests that combine values with AND and OR need an else-if chain. One habit: put break after default too, even though it's last. If someone adds a case below it later, nothing slides.
Quick Check
The Silver Tier Bonus
Quick check, back in the bonus program. This time the player's tier is S, for silver. How many bonus tokens does it print? Pause and predict. Build and run it. It prints six. C jumps straight to case S, so the gold line above never runs. Silver adds five, then falls through into bronze, which adds one. Then break stops it.
Wrap-Up
A Letter Typed Into a Number Menu
Back at the arcade, Priya rewrote a six-test prize chain as a switch. Sam tried keys one to six, then zero and seven, to see the default line. Then he pressed the letter a. Nothing sensible came back, because scanf with percent d can't read a letter. Menus need input checks, Priya said, and wrote it on her list. You'll build that check in lesson seven point seven.
Key Takeaways
The switch Statement in Review
To sum up. A switch looks at one whole-number selector, and jumps to the matching case. Without break, execution falls through into the next case. Clang warns only with W implicit fallthrough. Case labels must be single constants, never strings, decimals, or ranges. And default catches everything else. Give it a break too.
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 The switch Statement
How does a switch statement work in C?
What is fall-through in a C switch statement?
Can you use a string or a range in a C switch case?
When should you use a switch instead of an else-if chain 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 →