C switch fall-through with a default label before cases: determine program output
#include
int main()
{
int i=4;
switch(i)
{
default:
printf("This is default
");
case 1:
printf("This is case 1
");
break;
case 2:
printf("This is case 2
");
break;
case 3:
printf("This is case 3
");
}
return 0;
}
-
AThis is default This is case 1
-
BThis is case 3 This is default
-
CThis is case 1 This is case 3
-
DThis is default
-
ENo output
Answer
Correct Answer: This is default This is case 1
Explanation
Introduction / Context:This problem examines how a switch statement behaves when the switch expression does not match any case label, but there is a default label placed before other cases. It also checks understanding of fall-through and the effect of break.
Given Data / Assumptions:
- i equals 4; there is no case 4.
- The default label appears before case 1 and is not followed by a break.
- case 1 has a break; subsequent cases also contain breaks or end.
Concept / Approach:If no case matches, control jumps to default. Execution then continues sequentially until a break or the end of the switch. Because default is followed by case 1 without a break, the code “falls through” into case 1 and prints both lines.
Step-by-Step Solution:No case 4: jump to default.Execute printf → “This is default”.Fall through to case 1 → print “This is case 1”.Hit break at case 1 → exit switch. No other lines print.
Verification / Alternative check:Insert a break after default and re-run: only “This is default” would print. This demonstrates fall-through behavior.
Why Other Options Are Wrong:Other orders do not reflect control flow: case 3 never runs; printing only default ignores fall-through.
Common Pitfalls:Assuming default must appear last; forgetting that missing break allows fall-through; expecting an implicit break after default.
Final Answer:This is default This is case 1