Falling through a switch — Aptitude Question
Falling through a switch: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this C program print?
#include <stdio.h>
int main(void) {
int n = 2;
switch (n) {
case 1: printf("A");
case 2: printf("B");
case 3: printf("C"); break;
case 4: printf("D");
default: printf("E");
}
return 0;
}Options
- B
- BC
- BCD
- BCDE
Show the answer and the worked solution
Correct answer: B. BC
Worked solution
- n = 2 so control jumps to case 2 and prints B.
- There is no break after case 2, so execution falls through into case 3 and prints C.
- case 3 does end in break, so the switch is left and the output is BC.
Answer: BC.
The idea
Cases in C fall through by default; break is what stops them. Reading a switch as a chain that you jump into, rather than as a set of independent branches, makes the output obvious.
Shortcut. Enter at case 2 and print every label's output until the first break: B, then C, then break.
Common trap. "B" treats each case as a self-contained branch that stops at the next label; in C, cases fall through until a break.
All Programming Fundamentals questions · placement mock tests