The switch Statement, Explained with Code Examples

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

← Multi-Tier Decision Chains: else-if and Nested ConditionsNext lesson: Workshop: Menu-Driven Programs and Grade Calculators →

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

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.

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 The switch Statement

How does a switch statement work in C?
A switch evaluates one whole-number selector, such as an int or a char, and jumps directly to the case label with a matching constant. Execution continues from there until a break or the closing brace. The optional default label handles any value that no case matches. For a ride menu, switch (choice) with case 1, case 2 and case 3 sends each key straight to its ride.
What is fall-through in a C switch statement?
Fall-through happens when a case has no break, so execution slides into the next case's code, because a case label is only a landing spot. With the break after case 1 missing, choosing 1 also runs case 2. It can be useful: a gold tier can add 10 and fall through to silver's 5 and bronze's 1 for 16. Clang warns about unmarked fall-through only with -Wimplicit-fallthrough.
Can you use a string or a range in a C switch case?
No, standard C case labels must be whole-number constant expressions matched by exact equality. A string is not an integer, a double selector is rejected, and a label like case score >= 90 is not a constant. GCC and clang offer range labels only as a nonstandard extension. For text, decimals or ranges, use an else-if chain, or turn a range into one number, such as score / 10.
When should you use a switch instead of an else-if chain in C?
Use a switch when the question compares one value against exact whole numbers or characters, such as menu keys or letter grades. Use an else-if chain for ranges, decimals, text, or tests that combine values with && and ||. Neither is better in general, so pick the one that reads like the question. A useful habit is putting break after default too, so a case added later cannot fall into it.

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 →