🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Switch Case Rules in C
See each switch rule fail with a real gcc error, then learn the clean pattern for embedded decoders.
The switch case in C is the cleanest way to choose between many fixed values, and it is the backbone of command decoders, protocol parsers and state machines in firmware. It also has strict rules that most tutorials gloss over: case labels must be constants, continue is not allowed unless a loop surrounds the switch, and a missing break silently runs the next case. In this lecture of our free C programming course you will see each rule fail with a real gcc error message, then fix it. If you are working through this free C tutorial for embedded C programming interviews, these rules are asked about constantly.
What You Will Learn
- How a switch case in C selects and runs code, step by step
- Why case labels must be integer constant expressions, and what gcc says when they are not
- Why
continueinside a switch needs an enclosing loop, and howbreakdiffers inside a switch within a loop - How fall-through works, when it is useful and how to mark it as intentional
- Other switch errors: duplicate cases, non-integer expressions and unhandled enum values
- Safe patterns for embedded command decoders and state machines
Prerequisites
You should understand if-else chains, the for and while loops, character constants such as 'A', and the basics of enum and #define. The previous lecture on loop mistakes is useful because we combine switch with loops later on.
How the Switch Case in C Works
A switch evaluates one expression, compares the result with each case label, and jumps to the matching label. From that point it runs statements one after another, right through any following labels, until it meets a break or reaches the closing brace. If nothing matches, control jumps to default, or past the switch if there is no default.
Execution path of a switch statement
The important phrase is “run statements from that label”. A case label is only a jump target, it is not a wall. That is the origin of both the power and the danger of the switch case in C.
| Rule | Meaning | Example |
|---|---|---|
| Controlling expression is an integer type | int, char, enum and their variants; not float or double | switch (cmd) with cmd as char |
| Case labels are integer constant expressions | Literals, enum constants and macros, not variables | case 0x20:, case MODE_RUN: |
| No two labels with the same value | Duplicates are a compile error | Two case 1: lines fail |
| default is optional and can sit anywhere | It only runs when nothing else matches | Put it last by convention |
| break is optional | Without it, execution falls into the next label | See the fall-through section |
Rule 1: Switch Case in C Labels Must Be Constants
Case labels are resolved at compile time, so they must be constants the compiler can evaluate. Variables, even ones you never change, are not accepted. Look at what happens with two ordinary variables:
File: bad_case.c
#include <stdio.h>
int main(void)
{
int mode = 2, low = 1, high = 2;
switch (mode) {
case low: puts("low"); break;
case high: puts("high"); break;
}
return 0;
}$ gcc -std=c11 -Wall -Wextra -o bad_case bad_case.c
bad_case.c: In function ‘main’:
bad_case.c:8:5: error: case label does not reduce to an integer constant
8 | case low: puts("low"); break;
| ^~~~
bad_case.c:9:5: error: case label does not reduce to an integer constant
9 | case high: puts("high"); break;
| ^~~~The message “case label does not reduce to an integer constant” is the one to remember. A surprise for many learners: with gcc 13 in C mode, even a variable declared const int is rejected with the same message, because in C a const variable is still a variable, unlike in C++. The same compiler also reports “duplicate case value” when two labels carry the same number, and “switch quantity not an integer” if you switch on a double.
| Mistake | gcc 13 message | Fix |
|---|---|---|
| Variable as case label | case label does not reduce to an integer constant | Use an enum, a #define or a literal |
| const int as case label | case label does not reduce to an integer constant | Use an enum constant or #define |
| Two identical labels | duplicate case value | Remove or merge them |
| Switch on a double | switch quantity not an integer | Convert to an integer or use if-else |
The fix is to give the values proper constant names. An enum or a #define works, and an enum has an extra benefit that you will meet in a moment.
File: enum.c
#include <stdio.h>
enum mode { MODE_IDLE = 0, MODE_RUN = 1, MODE_SLEEP = 2 };
#define MODE_FAULT 9
static const char *describe(int m)
{
switch (m) {
case MODE_IDLE: return "idle";
case MODE_RUN: return "running";
case MODE_SLEEP: return "sleeping";
case MODE_FAULT: return "fault";
default: return "unknown";
}
}
int main(void)
{
int tests[] = { 0, 1, 2, 9, 5 };
int k;
for (k = 0; k < 5; k++)
printf("mode %d -> %s\n", tests[k], describe(tests[k]));
return 0;
}$ gcc -std=c11 -Wall -Wextra -o enum enum.c
$ ./enum
mode 0 -> idle
mode 1 -> running
mode 2 -> sleeping
mode 9 -> fault
mode 5 -> unknownValue 5 matches no label, so default returns “unknown”. Notice that the function returns straight from each case, so no break is needed there. Because the switch is on an int that happens to hold mode values, gcc cannot warn about missing enum cases. If you switch directly on a variable of the enum type and leave out a member and the default, -Wall adds the warning “enumeration value not handled in switch”. That is a strong reason to prefer enums for state machines.
Rule 2: Continue Needs a Loop, Break Does Not
Both break and continue look similar, but a switch only owns break. A switch is not a loop, so there is nothing for continue to continue. Try it:
File: bad_continue.c
#include <stdio.h>
int main(void)
{
char grade = 'A';
switch (grade) {
case 'A':
grade++;
continue;
default:
break;
}
return 0;
}$ gcc -std=c11 -Wall -Wextra -o bad_continue bad_continue.c
bad_continue.c: In function ‘main’:
bad_continue.c:10:9: error: continue statement not within a loop
10 | continue;
| ^~~~~~~~The error “continue statement not within a loop” is exact. Remove the loop requirement by putting the switch inside a loop, and continue then refers to that loop, skipping everything left in the current iteration, including the code after the switch. Inside a switch that sits in a loop, break leaves only the switch; the loop keeps going.
The next program scans a stream of characters, a miniature of a protocol decoder. Letters A and B are skipped with continue, a dash is counted with break, and anything else falls to default.
File: decoder.c
#include <stdio.h>
int main(void)
{
const char *stream = "AB-CD-E";
int ab = 0, sep = 0, other = 0, processed = 0;
int k;
for (k = 0; stream[k] != '\0'; k++) {
switch (stream[k]) {
case 'A':
case 'B':
ab++;
continue; /* belongs to the for loop: skips processed++ */
case '-':
sep++;
break; /* belongs to the switch only */
default:
other++;
break;
}
processed++;
}
printf("ab = %d, sep = %d, other = %d, processed = %d\n",
ab, sep, other, processed);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o decoder decoder.c
$ ./decoder
ab = 2, sep = 2, other = 3, processed = 5Trace for the stream AB-CD-E
| Char | Label hit | Statement | processed++ reached? |
|---|---|---|---|
| A | case A | ab++, continue | no, loop moves on |
| B | case B | ab++, continue | no |
| – | case dash | sep++, break | yes |
| C | default | other++, break | yes |
| D | default | other++, break | yes |
| – | case dash | sep++, break | yes |
| E | default | other++, break | yes |
Two characters (A and B) never reach processed++ because continue jumps to the next character, and five do, so the program prints processed = 5. This is the essential difference: break leaves the switch and the statements after it still run, while continue abandons them and moves the loop forward.
Fall-Through: Useful and Dangerous
Because a case label is just a jump target, leaving out break lets execution flow into the next label. Beginners meet this as a bug. Experienced engineers use it on purpose when cases should accumulate, for example a log level where “debug” should also enable everything below it.
File: fallthrough.c
#include <stdio.h>
enum level { LVL_ERROR = 1, LVL_WARN, LVL_INFO, LVL_DEBUG };
static void enable_logging(int level)
{
switch (level) {
case LVL_DEBUG:
puts(" + debug messages on");
/* fall through */
case LVL_INFO:
puts(" + info messages on");
/* fall through */
case LVL_WARN:
puts(" + warnings on");
/* fall through */
case LVL_ERROR:
puts(" + errors on");
break;
default:
puts(" (logging off)");
}
}
int main(void)
{
puts("level = INFO:"); enable_logging(LVL_INFO);
puts("level = ERROR:"); enable_logging(LVL_ERROR);
puts("level = 0:"); enable_logging(0);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o fallthrough fallthrough.c
$ ./fallthrough
level = INFO:
+ info messages on
+ warnings on
+ errors on
level = ERROR:
+ errors on
level = 0:
(logging off)Choosing INFO jumps into the middle of the chain and runs the info, warning and error lines, while ERROR runs only its own line. The comments /* fall through */ are not decoration: gcc with -Wextra recognises them and stays quiet, but if you remove one it warns “this statement may fall through”. That warning is how you catch the accidental kind.
| Kind | How it looks | What to do |
|---|---|---|
| Intentional fall-through | Documented with a comment or the fallthrough attribute | Keep it, and keep the comment next to it |
| Accidental fall-through | A forgotten break between two statements | Add break; enable -Wextra to be warned |
| Stacked labels | Several case labels on one statement | Fine: this is not fall-through of code |
Embedded Use Cases for the Switch Case in C
- Command decoders: a received byte selects a handler, with
defaultreporting an unknown command. - State machines: an enum state variable and a switch that moves between states on every tick of a timer.
- Register field decoding: masking a status register and switching on the result to select an action.
- Interrupt source dispatch: reading a cause code and switching to the matching service routine.
In all of these, the default label is your safety net. Hardware can deliver unexpected values from noise or a firmware version mismatch, and a default that logs and recovers beats undefined behaviour.
Common Mistakes and Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Two actions run for one input | Missing break | Add break, or comment the fall-through |
| Compile error on a case label | Variable or const int used as label | Switch to enum or #define |
| continue gives a compile error | No enclosing loop | Use break or restructure |
| Warning about a declaration right after a case label | Standard C before C23 wants a statement after a label; gcc 13 accepts it but warns under -pedantic | Add braces around the case body |
| New enum value not handled | No default and no -Wswitch warning noticed | Compile with -Wall and read warnings |
| Case on characters misses lowercase | Only uppercase labels written | Add lowercase labels or convert first |
Best Practices, Performance and Security
- Always write a default. Rule sets such as MISRA C:2012 require a default clause and a terminating break in every case (rules 16.3 and 16.4), so check your project standard.
- Use enums for states. They give readable names and allow the compiler to warn about unhandled values.
- Wrap case bodies in braces when you declare local variables inside them.
- Performance: compilers may implement a switch as a jump table or as a binary search, which often beats a long if-else chain, but do not assume. Measure on your target.
- Security: never leave a switch on external input without a default that rejects unknown values. Unvalidated commands are a classic attack surface.
Summary and Key Takeaways
- A switch case in C jumps to a matching label and runs on until break or the end.
- Case labels must be integer constant expressions; variables and const variables are rejected.
- continue is legal only when a loop surrounds the switch; break leaves just the switch.
- Fall-through is a feature, but mark it and let -Wextra check it.
- Always include default, and prefer enums for state variables.
Conclusion
Once you know these rules, the switch case in C stops being a source of surprises and becomes a precise tool for decoders and state machines. You have now seen each rule break with a real compiler message, which is the best way to remember it. Next we move to practical programs that process the digits of a number, a favourite topic in exams and interviews. Keep following this free embedded C course in order and compile every example yourself.
Frequently Asked Questions
What is a switch case in C?
It is a multi-way selection statement that evaluates an integer expression and jumps to the matching case label. Execution continues until a break or the end of the switch.
Why can I not use a variable as a case label in C?
Case labels must be integer constant expressions evaluated at compile time. Variables, including const-qualified ones, are rejected by gcc with the message that the case label does not reduce to an integer constant.
Can I use continue inside a switch in C?
Only when the switch is inside a loop. Then continue applies to the loop. Outside a loop gcc reports that the continue statement is not within a loop.
What does break do inside a switch within a loop?
It leaves only the switch. The loop keeps running and the statements after the switch still execute.
What is fall-through in a switch?
Execution running from one case label into the next because there is no break. It is useful for accumulating behaviour but should be commented as intentional.
Is the default case required?
The language does not require it, but good practice and standards such as MISRA C do. It gives you a safe path for unexpected values.
Can I switch on a string or float in C?
No. The controlling expression must have an integer type. For strings use strcmp in an if-else chain, and for floats convert or compare with relational operators.
Is a switch faster than if-else in embedded C?
Often, because compilers can generate jump tables or binary searches, but results depend on the compiler and the case values. Measure on your target before deciding.
Keep Going With the Free C Course
This free C tutorial gives students strong embedded C programming skills. Continue to the next lecture and write programs that process the digits of a number.

2 Comments