🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Switch Fall-Through Explained
Learn switch fall-through in C with a vending machine example. Free C programming course for embedded systems students.
Welcome to the next lesson of our free C programming course. Today we study switch fall-through in C: what happens when you leave out break, why that is sometimes the cleanest tool you have, and why it is also one of the most common sources of bugs in embedded C programming. This is part of the free C tutorial series on EmbeddedPathashala, written for students who want to write C for microcontrollers and firmware.
We build one small but realistic program, a vending-machine change calculator, and use it to learn the rule that makes fall-through work.
What You Will Learn
- How the C compiler picks an entry point in a switch and then keeps running downwards
- Why
switchfall-through in C is not a bug in the language but a defined behaviour - How to place
defaultat the top of a switch and why it still works - How to build a change-making routine that starts from any coin denomination
- How to mark intentional fall-through so compilers and reviewers stay quiet
- What MISRA C and the Linux kernel expect from fall-through in embedded projects
Prerequisites
- Basic
switchandcasesyntax from the previous lectures - Integer division
/and remainder%operators - A C compiler such as
gccon Linux, or any embedded toolchain that accepts C11
How Switch Fall-Through in C Really Works
A switch statement does not run one branch and stop. It evaluates the controlling expression, jumps to the matching case label, and then executes statements one after another from that point to the closing brace. The only things that stop the run are a break, a return, a goto, or the end of the block. The labels themselves are just markers, like addresses in assembly. Think of a switch as a computed jump into a straight list of instructions.
That is why the textbook tidy pattern, one break per case, is a habit and not a requirement. When you delete the break, control simply slides into the next case body. This is called fall-through, and it is legal, predictable and fully specified by the C standard.
Read the diagram top to bottom. The further up the list you enter, the more stages execute. Entering at the bottom runs a single stage. This staircase shape is exactly what a change-making algorithm needs: you try the biggest coin first, hand over what fits, and pass the leftover to the next smaller coin.
Real Example: Vending Machine Change
Imagine firmware for a coin-operated vending machine. It has four coin hoppers: 25, 10, 5 and 1 cent. Sometimes the 25 cent hopper is empty, so the controller must begin with 10 cent coins instead. The program below takes the change to return and the largest coin still available, then prints how many coins of each kind to dispense.
The complete program
#include <stdio.h>
int main(void)
{
int change; /* amount to return, in cents */
int largest; /* biggest coin hopper that has stock */
int count;
printf("Change to return (cents): ");
if (scanf("%d", &change) != 1 || change < 0) {
printf("Invalid amount\n");
return 1;
}
printf("Largest coin available (25/10/5/1): ");
if (scanf("%d", &largest) != 1) {
printf("Invalid coin\n");
return 1;
}
switch (largest) {
default:
printf("Unsupported coin value\n");
return 1;
case 25:
count = change / 25;
printf("25c coins: %d\n", count);
change %= 25;
/* fall through */
case 10:
count = change / 10;
printf("10c coins: %d\n", count);
change %= 10;
/* fall through */
case 5:
count = change / 5;
printf("5c coins : %d\n", count);
change %= 5;
/* fall through */
case 1:
printf("1c coins : %d\n", change);
}
return 0;
}
Line by line
switch (largest)picks the entry point. If the operator says 10, the 25 cent stage is skipped completely.- Each stage divides the remaining change by the coin value, prints the count, then keeps only the remainder with
change %= value. - No stage ends with
break, so the leftover flows into the next smaller coin automatically. - The last stage,
case 1, prints whatever is left. One cent coins can always make up the difference, so nothing needs to follow it. - The
defaultlabel sits at the very top and ends withreturn 1. Unknown coin values never reach any stage.
Build and run
gcc -Wall -Wextra -std=c11 -o coin_change coin_change.c
./coin_change
Expected output when all hoppers are stocked and the change is 97 cents:
Change to return (cents): 97
Largest coin available (25/10/5/1): 25
25c coins: 3
10c coins: 2
5c coins : 0
1c coins : 2
Now run it again with the 25 cent hopper empty:
Change to return (cents): 97
Largest coin available (25/10/5/1): 5
5c coins : 19
1c coins : 2
And once with an invalid coin:
Change to return (cents): 97
Largest coin available (25/10/5/1): 7
Unsupported coin value
Tracing 97 cents by hand
| Stage | Change before | Coins given | Change after |
|---|---|---|---|
| case 25 | 97 | 97 / 25 = 3 | 97 % 25 = 22 |
| case 10 | 22 | 22 / 10 = 2 | 22 % 10 = 2 |
| case 5 | 2 | 2 / 5 = 0 | 2 % 5 = 2 |
| case 1 | 2 | 2 | 0 |
Always trace one input on paper before you trust a fall-through chain. If your hand result differs from the program, the bug is almost always an order mistake: a smaller case placed above a bigger one.
Why default Can Come First
Many students believe default must be the last label. It does not. The compiler first looks for a matching case constant anywhere in the block. Only if nothing matches does it jump to default, wherever that label is written. Position matters in exactly one situation: fall-through. If default has no break or return, control continues into whatever case body is written below it.
That is why our program ends the default section with return 1. Without it, an invalid coin would drop straight into the 25 cent stage and print wrong results. Putting the error exit first also keeps the validation visible at the top, which many embedded teams prefer for readability.
| Layout | Behaviour | Typical use |
|---|---|---|
| default last, with break | Safe, most common style | General purpose code |
| default first, ends with return | Error exit read first, stages follow | Validation then staircase logic |
| default first, no jump | Falls into the next case body | Almost always a bug |
Marking Intentional Fall-Through
Modern compilers warn about fall-through because it is usually an accident. GCC and Clang report it with -Wimplicit-fallthrough, which -Wextra turns on. You tell the compiler and the next reader that it is deliberate in one of three ways:
| Method | Where it works | Example |
|---|---|---|
Comment /* fall through */ | GCC, Clang, most static analysers | Placed directly before the next case |
[[fallthrough]]; | C23 compilers | Statement before the next label |
__attribute__((fallthrough)); | GCC and Clang extension | Older toolchains |
fallthrough; macro | Linux kernel since 5.4 | Kernel and driver code |
Embedded rule to remember
MISRA C:2012 Rule 16.3 asks that every switch clause end with an unconditional break, which means fall-through needs a documented deviation. If your project follows MISRA, ask your lead before using this technique.
Where Fall-Through Helps in Embedded Systems
- Power-up and shutdown sequences: entering at stage N should also run every later stage, for example enable clock, release reset, configure pins.
- Cleanup levels: a failure at step 3 should undo step 3, step 2 and step 1 in order.
- Grouped inputs: several case labels stacked together share one body, which is fall-through with empty bodies.
- Change and denomination logic: as in our example, ATMs, ticket machines and billing counters.
Performance note
A switch with dense constant labels is often compiled into a jump table, so the entry is a single indexed jump regardless of how many cases exist. Fall-through then costs nothing extra, it is just the instructions running in order. Sparse labels like 25, 10, 5, 1 may become a short compare chain instead. Either way, the cost is tiny compared with a printf over a UART.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Counts are too large | Cases listed smallest to largest | Reorder from largest to smallest |
| Unknown input prints results | default has no return or break | End default with return or break |
| Compiler warning about fall-through | Intentional but unmarked | Add the comment or attribute |
| Error: a label can only be part of a statement | Declaration directly after case label (before C23) | Wrap the case body in braces |
| Wrong remainder | Used = instead of %= | Use change %= value |
Warning
Never rely on fall-through without a comment. Six months later, you or a teammate will see a missing break and add one, silently breaking the staircase.
Best Practices
- Keep fall-through chains short and ordered, with the order explained in a comment.
- Mark every intentional fall-through so tools can tell it from a mistake.
- Validate input before the switch, or use a
defaultthat exits. - Compile with
-Wall -Wextraand treat the warnings as errors in your build. - Test the first entry, the last entry and one invalid entry for every switch you write.
Security note
Treat the controlling value as untrusted if it arrives over UART, Bluetooth or a network. An unchecked value that falls into the wrong stage can skip security checks. Always have a safe default.
Summary and Key Takeaways
- A switch jumps to a label and runs onward until something stops it.
- Removing break creates fall-through, which is defined behaviour.
- Order cases from the stage that must run first to the stage that runs last.
- default can be anywhere, but it must end with a jump if it should not fall through.
- Always mark intentional fall-through and follow your project coding standard.
Conclusion
Switch fall-through in C is a sharp tool. Used carefully it turns a long chain of if statements into a short, readable staircase, and it matches the way hardware sequences actually run. In the next lecture of this free embedded C course we use the same trick to count the days of a year from a date, then build on it to find the day of the week.
Frequently Asked Questions
What is switch fall-through in C?
It is the behaviour where, after a matching case runs, execution continues into the next case body because no break stops it.
Is fall-through allowed in the C standard?
Yes. It is fully defined. Compilers only warn because it is often unintended.
Can default be placed at the top of a switch?
Yes. It is chosen only when no case matches, regardless of position. Just end it with return or break if you do not want it to fall into the next case.
How do I silence the implicit fall-through warning?
Add a fall through comment, use [[fallthrough]] in C23, use __attribute__((fallthrough)) with GCC or Clang, or use the fallthrough macro in Linux kernel code.
Does MISRA C allow fall-through?
MISRA C:2012 Rule 16.3 requires an unconditional break at the end of every switch clause, so fall-through needs a formal deviation.
Why must the cases be in descending order in the change example?
The program should try the biggest coin first. Each stage passes its remainder to the next, so a smaller coin placed first would take the whole amount.
Is a switch faster than if-else in embedded C?
Often yes, because the compiler can use a jump table, but check the generated assembly for your target before assuming.
Practice task
Add a 50 cent hopper above the 25 cent case and test it with change values 99 and 49. Then try starting the switch at 50, 25 and 5.
Keep Learning Embedded C for Free
Continue the free C tutorial with the next lecture on counting days of the year.

2 Comments