What is the output of this <code>switch</code> statement in C? Note the statement before any <code>case</code> label. #include<stdio.h> int main() { int i = 1; switch (i) { printf("Hello\n"); case 1: printf("Hi\n"); break; case 2: printf("Bye\n"); break; } return 0; }

Difficulty: Easy

Correct Answer: Hi

Explanation:


Introduction / Context:
This question checks knowledge of switch control flow. Statements inside a switch that precede any case label are not “default prelude” statements; control transfers directly to the matching case label, skipping earlier statements.


Given Data / Assumptions:

  • i = 1.
  • There is a printf("Hello\n"); placed before the case labels.
  • Standard C switch semantics apply: jump to the matching label and execute from there.


Concept / Approach:
When switch (i) is executed, the implementation looks for a matching case label (here case 1) and transfers control directly to that label. No statement before that label will run. Therefore, only the statements under case 1 (up to the break) execute.


Step-by-Step Solution:

Evaluate switch (1) → jump to case 1.Execute: printf("Hi\n");.Encounter break → exit the switch.


Verification / Alternative check:
Move printf("Hello\n"); after case 1: and before the printf("Hi\n");. Then both lines will print; this confirms the role of label placement.


Why Other Options Are Wrong:

Options including “Hello” assume the pre-label statement executes; it does not.“Bye” corresponds to case 2, which does not match.“No output” contradicts the executed printf in case 1.


Common Pitfalls:
Assuming topmost statements run before label dispatch; forgetting that code before the first case is dead unless jumped to.


Final Answer:
Hi.

More Questions from Control Instructions

Discussion & Comments

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