C Programming Basics
int n = 2, c = 0;
switch (n) {
case 1: c += 1;
case 2: c += 10;
case 3: c += 100; break;
default: c += 1000;
}
printf("%d\n", c);Which of the following is the output when the switch statement above, which contains a case without break, is executed?
- A10
- B110
- C1110
Show answer and explanation
Answer: B. 110
A switch statement jumps to the case label matching the value of n and from there keeps executing the statements of the following cases until it meets a break (fall-through). n is 2, so execution starts at case 2, and after c += 10 it also executes c += 100 of case 3, then leaves the switch at break. c is 10 + 100 = 110. When falling through is intended, saying so in a comment makes it easy to tell apart from a forgotten break.
- A. There is no break after case 2, so the statement of case 3 is also executed.
- B. Correct. case 2 and case 3 run in sequence, and break leaves the switch.
- C. The break after case 3 leaves the switch, so the default statement is not executed.