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 →
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.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
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.
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-Case Mechanism
How do you write a switch statement with case labels and a default in C++?
What data types can you use in a switch statement in C++, and why not double or string?
What happens if you forget the break in a switch case?
When should I use a switch instead of an if-else if ladder in C++?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →