C language – switch body semantics and fall-through behavior: Identify whether this program has a compilation error and what it prints. #include <stdio.h> int main() { int i = 1; switch (i) { printf("This is c program."); case 1: printf("Case1"); break; case 2: printf("Case2"); break; } return 0; }

Difficulty: Medium

Correct Answer: No Error and prints "Case1"

Explanation:


Introduction / Context:
This question explores what statements are permitted inside a switch compound statement and how control is transferred to the matching case label. It clarifies whether code before the first label is legal and whether a default is required.


Given Data / Assumptions:

  • i equals 1, so the matching label is case 1:.
  • A printf appears before any case labels inside the switch block.
  • No default label is present.


Concept / Approach:
In C, a switch statement’s body is an ordinary compound statement that may contain labels. Execution jumps directly to the statement with the matching case (or default). Unlabeled statements earlier in the block are skipped; they are legal but not executed. A default label is optional and its absence is not an error.


Step-by-Step Solution:
Switch on 1 → control transfers to case 1:.The unlabeled printf before case 1 is not executed.printf("Case1") runs and then break exits the switch.


Verification / Alternative check:
Compilers accept statements before the first label; no diagnostic is required. Running the program prints “Case1”.


Why Other Options Are Wrong:
No default specified — not mandatory. Invalid printf after switch — it is legal; it is simply not reached.


Common Pitfalls:
Believing all statements in a switch must be labeled; assuming missing default is an error.


Final Answer:
No Error and prints "Case1"

More Questions from Control Instructions

Discussion & Comments

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