Switch Statements
Why we need switch
Analogy
- You are building the menu for an ATM: 1 checks the balance, 2 withdraws, 3 deposits, 4 prints a statement, 5 exits.
- You could write it as a chain of
ifandelse if. It works. - But look at what you typed: you wrote
choice ==five separate times. You are asking the same question about the same variable over and over, and the repetition hides the actual point, which is a simple list of options. switchis built for exactly that shape.
What is a switch?
Definition
A switch looks at one value once, then jumps straight to the label that matches it.
switch (value) names the thing being tested. case X: is a label meaning "if the value is X, start here". break means "we are done, leave". default is the catch-all, the else of the switch.
The variable is named a single time at the top, and under it sits a flat list of options anyone can scan in two seconds.
switch (choice) { case 1: checkBalance(); break; case 2: withdraw(); break; default: exit();}Fall-through, which catches everybody once
Leave out a break and something strange happens.
Here is why. A case is not a container. It is a doorway. The switch jumps in at the matching label and then keeps running straight down through everything below it, ignoring the other labels completely, until it hits a break or reaches the end.
break is not decoration. It is the wall that stops the flow.
Watch out
When you forget it, the bug is quiet. Your program does not crash. It just does extra things, and you will stare at the code for twenty minutes before you see it.
Fall-through on purpose
Once you understand it, it becomes useful. Stack labels with nothing between them to group options:
switch (day) { case 6: case 7: print("Weekend"); break; default: print("Weekday");}Case 6 has no body, so it falls straight into case 7. Both give "Weekend". This is a clean, standard pattern rather than a trick.
What a switch cannot do
This is where beginners get stuck, so be clear about the limits. A switch compares one value against fixed, exact options. That is all.
- No ranges. You cannot write
case marks > 90. - No conditions. Nothing combined with
andoror. - Labels must be constants, known before the program runs. A variable cannot be a label.
- Only some types. Integers and characters everywhere, strings in modern Java, C# and JavaScript. Floats almost never, because exact equality on floats is unreliable anyway.
If your decision needs a range or a combined condition, switch is the wrong tool.
| switch | if / else | |
|---|---|---|
| Good for | One variable, many fixed values | Ranges, and combined conditions |
| Typical use | Menus, states, commands, weekdays | Anything with a comparison in it |
| Shape | A flat list, scannable at a glance | A chain, read top to bottom |
Rough guide: exact matches on one value go to switch, everything else goes to if / else.
Python does not have one
If Python is your first language this chapter looks like a foreign country, because Python deliberately left switch out. Three things you use instead.
A chain. Perfectly normal and idiomatic: if, elif, else.
A dictionary. When each case just calls a function, this is elegant:
actions = { 1: check_balance, 2: withdraw, 3: deposit,} action = actions.get(choice, exit) # exit is the defaultaction()match, from Python 3.10. The closest thing to a switch, and more powerful:
match choice: case 1: check_balance() case 2: withdraw() case 6 | 7: weekend() case _: exit()Two differences from the C-style switch. match has no fall-through, so no break is needed. And case _ is the default.
Note
Newer Java and JavaScript offer an arrow form that removes fall-through entirely and returns a value: case 6, 7 -> "Weekend";. If your language supports it, prefer it. No break, no accidents, and the whole thing produces a value you can assign.
Mistakes to watch for
Watch out
- Forgetting
break, causing silent fall-through. The number one switch bug by a distance. - Forgetting
default, so an unexpected value does nothing at all. - Trying to use a range or a condition in a case label.
- Using a variable as a label. Labels must be constants.
- Assuming Python has a switch. It has
match, and only from 3.10.
Quick recap
switchtests one value against a list of exact options- A
caseis a doorway, not a box. Execution falls through until abreak defaultcatches everything that matched nothing- Stacked cases with no body are a deliberate way to group options
- No ranges, no conditions, no variable labels
- Python uses a chain, a dictionary, or
match
Key takeaway
A case is a doorway into the switch, and break is the only thing that stops you walking through the rest of the house.