The Switch-Case Mechanism, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 4.5 Free with a free account

The Switch-Case Mechanism

C++ Programming · Chapter 4: Decision MakingSection 4.5 · lesson 25 of 84video coming soon

← Routing Execution With if and elseNext lesson: Deeply Nested Conditions →

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

In this lesson

Selecting among many fixed options.

  • Write a switch with case labels and a default
  • Say which types may be tested, and why
  • Predict what a missing break does
  • Choose between a switch and a ladder

Transcript

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

Opening Problem

Why Ladders of Comparisons Read Badly

When one value has to be checked against a long list of fixed possibilities, a ladder of comparisons works, but it reads badly. Look at the repetition. Every rung asks the same question: is code equal to this fixed value? Writing the variable's name on every rung gives you that many chances to write the wrong name. Switch exists for exactly this: one expression, many labeled destinations, and a jump straight to the matching one. It's narrower than the ladder it replaces. And it has one famous trap built into its design.

Anatomy

The Named Parts of a Switch

Here's the shape of a switch, with every part named. Switch, with code in parentheses, supplies the controlling expression. Case 1, followed by a colon, is a label: a destination control may arrive at. Under it come the statements for that label. Then break, which leaves the switch entirely. Case 2 prints withdrawal, and breaks. And default is where control goes if nothing matched. With code equal to 2, control jumps straight to case 2, prints withdrawal, and leaves.

Rules

Rules Attached to Each Part

Each part comes with a rule. The controlling expression is evaluated exactly once. Each case value must be a constant known when the program is built, and unique within this switch. Break is not automatic. Without it, execution carries on into the next label's statements. Default is optional, and there's at most one. If it's absent and nothing matches, the whole switch does nothing. And the braces hold the whole body, belonging to the switch as a whole, not to each label.

Allowed Types

Whole-Number-Like Controlling Expressions and Char Labels

This is where switch is genuinely narrower than a ladder. The controlling expression must produce a whole-number-like value: an integer, a character, a truth value, or a named set of constants. A char works, because a character is a small whole number, so the labels are written like case, quote A, quote. Here the letter is B, so control jumps to the second label. Only the second label ran, exactly as expected.

Illegal Expressions

Doubles and Text Are Rejected

A double is rejected, because fractional values can't be reliably compared for exact equality. The compiler says so plainly. Text is rejected too, since it isn't a whole-number type. Comparing text needs a ladder.

Illegal Labels

Variables and Conditions Cannot Be Labels

Labels are restricted as well. A variable can't be a label, because a label must be known when the program is built. A condition like x greater than 10 can't be a label either, because a label is a value to match, not a question.

Duplicates and Payoff

No Repeated Values, Fast and Clear Code

And no value can appear twice: two identical labels would mean two destinations. Those restrictions are why a switch is fast and clear. Every label is a fixed whole number known in advance, so a reader sees at a glance that one value is being matched, with no hidden conditions.

Quick Check

The Famous Fall-Through Trap

Here's the famous trap. A case label is a destination, not a container. Control jumps to the matching label, then keeps running downward until it meets a break, or the closing brace. Case A prints excellent, but has no break. Quick check: what does an input of A print? Pause, and trace it.

Answer

Legal, Silent, and Wrong Output

Two lines. Excellent, and then Good. Control lands on case A, prints excellent, then falls straight into case B and prints good as well, before it finally meets a break. The other inputs behave. B prints good. C prints satisfactory. And Z goes to default. That's what makes the fault expensive. It compiles, it runs, and three of the four inputs are perfect. A tester who tries a middle-of-the-road value never sees it. Legal, silent, and wrong.

Useful Fall-Through

Grouping Labels for Shared Treatment

Fall-through is also a feature, and two uses justify it. The common one is grouping. Stack several labels with nothing between them, and it means: any of these values, same treatment. Months 1, 3, 5, 7, 8, 10 and 12 all print 31 days. Months 4, 6, 9 and 11 print 30. And month 2 prints 28 or 29. There are no statements to fall past, so it isn't really fall-through in spirit. As a ladder, that first group would need seven comparisons joined by OR, naming the variable seven times. The grouped form states it as a list of values, which is what it really is.

Cascade

Deliberate Cascades and Marking Intent

The other use is a genuine cascade. Each label adds something, then continues into the next, so a higher level gets everything the lower ones get. Level 3 prints reports, falls into level 2, which prints editing, then into level 1, which prints viewing, and breaks. So level 3 prints all three lines, and level 1 only the last. But a reader can't tell an intended fall-through from a forgotten break just by looking. So mark it, with the standard attribute, fallthrough in double square brackets. It records the intent. Take it away, and with the right warning switched on, clang flags the label. An unmarked fall-through will be fixed by the next person who touches the file.

Default Label

Why Nearly Every Switch Needs Default

If no label matches and there's no default, the switch simply does nothing, and the program continues. Sometimes that's intended. Far more often, a value nobody anticipated passed through in silence. So include a default in almost every switch. Even if it only reports the value as unexpected, that turns an invisible fault into a visible one. It goes last, where readers expect it. And it still needs a break if anything follows it. Writing one is free documentation of what the program considers unexpected.

Decision Guide

Three Questions for Choosing Switch

Three questions settle whether to use a switch. Is one single value being tested? Is it a whole number or a character? And are the targets fixed values, rather than ranges? If all three answers are yes, use a switch. Any no leads to an else if ladder. A range, like 50 to 59, needs a ladder, since there are no range labels. Fractions, text, and conditions combining several variables all need a ladder. And with only two or three possibilities, the switch costs more lines than it saves.

Common Mistake

Declarations Skipped by a Jump

One more mistake to recognize on sight. All the labels share one body, so a variable declared under case 1 still exists under case 2. But if control jumped straight to case 2, the line that initialized it was skipped. The compiler refuses. Wrapping that label's statements in their own braces confines the variable, and fixes it.

Key Takeaways

Summary and Score Range Challenge

To summarize. A switch matches one whole-number or character value against fixed, unique labels. Labels are destinations, not containers. Without a break, execution falls through. Group labels for shared bodies, and mark any deliberate cascade. Always include a default. And ranges, text and fractions need a ladder instead. Here's something to think about. Scores from 0 to 49, 50 to 74, and 75 to 100 each need different handling. Can that be written as a switch? Justify your answer.

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 The Switch-Case Mechanism

How do you write a switch statement with case labels and a default in C++?
A switch evaluates one controlling expression in parentheses once, then jumps to the matching case label, with an optional default for everything else. For example: switch (code) { case 1: std::cout << "Deposit"; break; case 2: std::cout << "Withdrawal"; break; default: std::cout << "Unknown"; } With code equal to 2, it prints Withdrawal and leaves at the break. Each case value must be a unique constant.
What data types can you use in a switch statement in C++, and why not double or string?
A switch expression must produce a whole-number-like value: an integer, a char, a bool, or an enumeration. A char works because a character is a small whole number, so labels look like case 'A':. A double is rejected because fractional values can't be reliably compared for exact equality. Text such as std::string is rejected because it isn't a whole-number type, so comparing text needs an if-else ladder.
What happens if you forget the break in a switch case?
Execution falls through, running the next label's statements until it reaches a break or the closing brace. Suppose case 'A' prints Excellent with no break, and case 'B' prints Good and then breaks. An input of A prints both Excellent and Good. The code compiles and runs, so the bug is easy to miss. Mark deliberate fall-through with [[fallthrough]] so readers can tell it from a mistake.
When should I use a switch instead of an if-else if ladder in C++?
Use a switch when you are testing one single value, that value is an integer or a character, and each target is a fixed value rather than a range. If any answer is no, use an else if ladder. Ranges like 50 to 59, fractions, text, and conditions involving several variables all need a ladder. With only two or three possibilities, a switch usually costs more lines than it saves.

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 →