The switch Statement
When testing a single variable against multiple fixed integer or character values, an if-else ladder can become verbose. The switch statement offers a clean, efficient multi-way branch.
switch(expression)?Syntax Rules of switch-case
To use switch effectively in C, you must understand its strict compile-time rules and integral requirements.
4 Golden Rules of switch
- 1. Integral Types Only: The control expression must evaluate to an
int,char, orenum. Floating point numbers (float,double) and strings are illegal! - 2. Constant Case Labels: Each
caselabel must be a compile-time constant (e.g.,case 5:orcase 'X':). Variables likecase x:are not allowed. - 3. Unique Case Values: Duplicate case values in the same switch block cause a compiler error.
- 4. Optional Default Clause: The
default:block runs if no cases match. It can be placed anywhere, but is typically at the bottom.
Interactive Calculator Lab
Fallthrough & The break Statement
Unlike high-level languages like Python, C does not stop after executing a matching case. Without a break statement, execution falls through to all subsequent cases!
Interactive Fallthrough Simulator
break; Statements
When to Use switch vs if-else
Choosing between switch and an if-else ladder depends on your data types, condition complexity, and performance goals.
| Feature / Characteristic | switch-case Statement |
if-else if-else Ladder |
|---|---|---|
| Condition Type | Tests for exact equality (`==`) against constant values. | Evaluates relational & logical expressions (`<`, `>`, `&&`, `||`). |
| Supported Data Types | Restricted to integral types (`int`, `char`, `enum`). | Supports all data types (`float`, `double`, pointers, etc.). |
| Compiler Mechanics | Compilers often build an $O(1)$ Jump Table for speed. | Sequential evaluation line-by-line ($O(N)$ execution time). |
| Readability | Extremely clean for large menu selections (10+ options). | Can become cluttered with nested parentheses and braces. |
The break and continue Statements
Jump statements alter the normal flow of control by transferring execution to another part of your code immediately.
Interactive Jump Statement Tracer
Loop counts from i = 1 to 5. Select what happens when i == 3:
The goto Statement & Labels
The goto statement transfers execution unconditionally to a specified named label within the same function.
Syntax & Label Definition
Define a label followed by a colon (my_label:), then jump to it anywhere in the function using goto my_label;.
Why `goto` is Discouraged
Overusing goto creates spaghetti code that makes program control flow difficult to trace, debug, and maintain.
Valid Modern Exception
The only widely accepted use of goto in modern C (e.g., Linux Kernel) is jumping out of deeply nested loops directly to clean up resources upon error.