2.2switch and fall-through
The idea
A switch jumps to the matching case label and then keeps running every statement below it until a break.
Think of it like this: Stepping onto a moving walkway: once you are on at some stop, you ride to the end unless you jump off (break).
Why it exists
Forgotten breaks are the classic trap; GATE shows a switch with no break and asks what is printed.
How it works
- Evaluate the switch expression.
- Find the case with an equal constant; if none, go to default (wherever it is written).
- Run from there downward, ignoring labels, until a break or the closing brace.
Worked example: case 'A' with no breaks
All statements from case 'A' to the end run: Choice A, Choice B, No Choice, in that order.
Now play with it
- →Step through the fall-through tab and watch the line highlight skip over labels.
- →Try default in the middle.
Each case ends with break, so only the matching case runs.
1#include <stdio.h>2int main() {3 int d = 2;4 switch (d) {5 case 1: printf("one "); break;6 case 2: printf("two "); break;7 case 3: printf("three "); break;8 default: printf("other ");9 }10 printf("done\n");11 return 0;12}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
switch (2) { case 1: printf("a"); case 2: printf("b"); case 3: printf("c"); break; case 4: printf("d"); } prints
Exam notes (the dense version)
A switch jumps to the matching case label and then keeps running every following statement, through later labels and the default, until a break (or the closing brace). Labels must be integer constants and may be grouped. The default label can appear anywhere.
Previous year questions: Control Flow & Output (10)
PYQs are grouped by topic, so this is the full set for Control Flow & Output; try the ones that match this subtopic. Open all 10 on the topic page.