C switch fall-through with a default label before cases: determine program output\n\n#include<stdio.h>\nint main()\n{\n int i=4;\n switch(i)\n {\n default:\n printf("This is default\n");\n case 1:\n printf("This is case 1\n");\n break;\n case 2:\n printf("This is case 2\n");\n break;\n case 3:\n printf("This is case 3\n");\n }\n return 0;\n}

Difficulty: Medium

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

More Questions from Control Instructions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion