🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Switch Statement Syntax
Master the switch statement in C: syntax, valid and invalid expressions, case constant rules, compiler errors and embedded command-decoder examples in this free C tutorial.
The switch statement in C picks one path out of many based on the value of a single integer expression. Firmware is full of such decisions: decode a command byte from a UART, dispatch a state in a state machine, choose a clock divider from a mode number. A long if-else ladder can do the same job, but a switch states the intent directly and often compiles to faster code. This lecture of our free C programming course concentrates on the syntax and on what the compiler accepts and rejects.
As in the rest of this free C tutorial, every program was compiled and run, and every error message is real GCC output. If you are working through a free embedded C course to prepare for firmware interviews, embedded C programming questions about switch are guaranteed, so we go slowly through the rules. How execution flows between cases, including break and fall-through, is covered in a later lecture.
What You Will Learn
- The complete syntax of the switch statement in C, with case and default
- Which expressions are legal after the switch keyword and which are not
- Which constants are legal after case and the five common ways to get them wrong
- How to use constant expressions, enumerations and macros as case labels
- How switch statements can be nested
Prerequisites
You should understand integer and character types, relational and logical operators, and the if-else statement. The previous lectures on break and goto help you read the examples, because every case in our programs ends with a break.
Switch Statement in C: General Syntax
switch (expression)
{
case constant1:
statements;
break;
case constant2:
statements;
break;
/* more cases */
default:
statements;
}
Four keywords appear: switch, case, default and, in practice, break. The expression is evaluated once. Its value is compared with each case constant, and execution begins at the matching label. If nothing matches, execution begins at default, if one exists. The default label is optional, you may have at most one, and it does not have to be last, although placing it last is the usual style.
How the switch selects a path
Example 1: A Motor Command Decoder
A motor controller receives a one-character command. The switch maps each command to an action.
#include <stdio.h>
int main(void)
{
char cmd = 'R';
switch (cmd) {
case 'S':
printf("Starting motor\n");
break;
case 'P':
printf("Pausing motor\n");
break;
case 'R':
printf("Reversing motor\n");
break;
default:
printf("Unknown command\n");
}
return 0;
}
$ gcc -std=c11 -Wall sw1.c -o sw1
$ ./sw1
Reversing motor
Change cmd to ‘S’, ‘P’ or ‘X’ and rebuild to see the other branches. The character constants work because a char is an integer type; each one is just its character code, such as 82 for ‘R’ in ASCII.
Rules for the Switch Expression
The expression in parentheses must have an integer type. That includes char, short, int, long, long long, their unsigned forms, and enumerations. It can be a variable, a constant, a function call returning an integer, or any arithmetic, relational, logical or bitwise expression that produces an integer. Floating-point expressions are not allowed. Characters are fine because they are converted to their integer codes.
| Expression | Legal? | Reason |
|---|---|---|
switch (mode) with int mode | Yes | Integer variable |
switch (temp > limit) | Yes | Relational result is 0 or 1 |
switch (digit - '0') | Yes | Arithmetic on char gives int |
switch (get_mode()) | Yes | Function returning int |
switch (big) with long big | Yes | long is an integer type |
switch (f) with float f | No | Floating-point type |
switch (a + 4.5) | No | Result is double |
Example 2: Valid Switch Expressions in Action
#include <stdio.h>
static int get_mode(void) { return 2; }
int main(void)
{
int temp = 75, limit = 60;
char digit = '7';
long big = 3L;
short small = 1;
switch (temp > limit) {
case 1: printf("Over limit\n"); break;
case 0: printf("Within limit\n"); break;
}
switch (digit - '0') {
case 7: printf("Digit is seven\n"); break;
default: printf("Other digit\n");
}
switch (get_mode()) {
case 2: printf("Mode two\n"); break;
default: printf("Other mode\n");
}
switch (big) {
case 3: printf("long matched 3\n"); break;
}
switch (small) {
case 1: printf("short matched 1\n"); break;
}
return 0;
}
Over limit
Digit is seven
Mode two
long matched 3
short matched 1
The first switch is a neat embedded idiom: a comparison yields 1 or 0, and the two cases act like an if-else. The second converts an ASCII digit to its numeric value by subtracting ‘0’, a trick used constantly when parsing UART text.
Rules for Case Constants
Each case label must be an integer constant expression: something the compiler can evaluate while compiling. That allows integer literals, character literals, enumeration constants, macros that expand to constants, and arithmetic on any of those. These rules follow:
- Every case value must be different from every other in the same switch.
- Case values must be integer or character constants. Floating-point and string constants are not allowed.
- Variables are not allowed, even variables that happen never to change.
- Each case label takes exactly one value; you cannot write a list of values after one case keyword.
- A case may be followed by any number of statements, or none, and braces around several statements are optional.
| Case label | Legal? | Note |
|---|---|---|
case 4: | Yes | Integer literal |
case 'A': | Yes | Character literal |
case 2 + 4: | Yes | Constant expression, value 6 |
case 'a' > 'b': | Yes | Constant expression, value 0 |
case "second": | No | String constant |
case 2.3: | No | Floating-point constant |
case a: | No | Variable |
case a + 2: | No | Depends on a variable |
case 2, 4, 5: | No | Multiple values in one label |
Example 3: Constant Expressions, Macros and Enums
#include <stdio.h>
#define BASE 10
enum { IDLE, RUN, FAULT };
int main(void)
{
int code = 12;
switch (code) {
case BASE + 2:
printf("BASE + 2 matched\n");
break;
case RUN:
printf("RUN\n");
break;
case 'A' + 1:
printf("letter B code\n");
break;
case 3 * 4 + 1:
printf("thirteen\n");
break;
}
return 0;
}
BASE + 2 matched
The labels have values 12, 1, 66 and 13, all different, so the compiler is happy. In real firmware, enumerations and macros are the best case labels, because a name like STATE_RUN documents itself far better than a bare number.
What the Compiler Says About Invalid Switches
Each invalid form produces a specific GCC 13 error. Recognising these messages saves a lot of debugging time.
switch (f) { case 1: ... } /* f is a float */
error: switch quantity not an integer
switch (x) { case "one": ... }
error: pointers are not permitted as case values
switch (x) { case a: ... } /* a is a variable */
error: case label does not reduce to an integer constant
switch (x) { case 1: ... case 2 - 1: ... }
error: duplicate case value
switch (x) { case 2, 4, 5: ... }
error: expected ':' or '...' before ',' token
Look at the last message. It mentions '...' because GCC supports a non-standard range extension, case 2 ... 5:. It works only on GCC and Clang, it is not portable C, and it should be avoided in code that may be built with other compilers. To match several values portably, stack the labels one after another, a technique explained fully in the lecture on case flow.
Nesting Switch Statements
A case may contain any valid statement, including another switch. This is called nesting. Inner and outer switches are independent, so the same case values may be reused.
#include <stdio.h>
int main(void)
{
int state = 2, sub = 1;
switch (state) {
case 1:
printf("State 1\n");
break;
case 2:
switch (sub) {
case 0: printf("State 2 / sub 0\n"); break;
case 1: printf("State 2 / sub 1\n"); break;
}
break;
}
return 0;
}
State 2 / sub 1
Notice that the inner break belongs to the inner switch, so the outer case needs its own break. Deeply nested switches are hard to read; prefer a helper function for each sub-state.
Nested switch: state 2, sub-state 1
Switch vs If-Else Ladder
| Aspect | switch | if-else ladder |
|---|---|---|
| Condition type | Equality of one integer against constants | Any condition, ranges, floats, strings |
| Readability for many branches | High | Drops as branches grow |
| Typical code generation | Jump table or compare tree, chosen by the compiler | Sequential tests |
| Best embedded use | Command decoding, state machines | Range checks like temperature bands |
Compilers choose how to implement a switch. When case values are dense, a jump table gives constant-time dispatch; when they are sparse, a series of comparisons or a binary search is used. You never need to decide, but dense values such as 0, 1, 2, 3 tend to be cheapest.
Real-World Uses in Embedded C Programming
- Command decoding: map the first byte of a UART or CAN message to a handler.
- State machines: one case per state, with the current state in an enum.
- Register configuration: choose timer prescaler settings from a mode number.
- Menu systems: dispatch key codes to screen actions on a small display.
Common Mistakes
- Using a float or double as the switch expression.
- Using a variable as a case label.
- Repeating a case value, often through two different macros that happen to be equal.
- Writing several values after one case keyword.
- Using a string, such as a command name, as a case label; compare strings with strcmp in an if chain instead.
- Forgetting break, which we investigate in the lecture on case flow.
Best Practices
- Use enumerations or named constants for case labels.
- Always include a default case, even if it only reports an error. For enumerations, it helps catch values added later.
- Keep each case short; call a function when the work is long.
- Terminate each case with break unless you deliberately want it to continue, and comment the exception.
- Compile with
-Wall -Wextra; GCC can warn about unhandled enumeration values.
Summary and Key Takeaways
- The switch expression must be an integer type; floats are rejected.
- Case labels must be distinct integer or character constant expressions, one value per label.
- Strings, floats, variables and value lists are all illegal as case labels.
- The default label is optional and catches non-matching values.
- Switch statements can be nested, and each has its own breaks.
You now know what is legal in a switch statement in C. Test yourself with the quiz and interview questions in the next lecture of this free C programming course. After that, we follow the execution flow inside a switch, including break, fall-through and default placement.
Frequently Asked Questions
What types can a switch expression have in C?
Any integer type, including char, short, int, long, long long, unsigned types and enumerations. Floating-point types are not allowed.
Can I use a string in a switch case in C?
No. String constants are not allowed as case labels. Use strcmp with an if-else chain, or map strings to enum values first.
Can a case label contain a variable?
No. Case labels must be constant expressions the compiler can evaluate at compile time.
Is default required in a switch statement?
No, it is optional, but including it is good practice because it handles unexpected values.
Can two cases have the same value?
No. Duplicate case values cause the error “duplicate case value”.
Is switch faster than if-else in embedded C?
Often yes for many dense values, because the compiler may use a jump table, but the compiler decides. Choose switch for clarity first.
Your Free C Programming Course Continues
Next in this free embedded C course: a quiz and interview questions covering continue, goto, nested loops and switch syntax.

2 Comments