What is the output of this switch statement in C? Note the statement before any case label.
#include
int main()
{
int i = 1;
switch (i)
{
printf("Hello
");
case 1:
printf("Hi
");
break;
case 2:
printf("Bye
");
break;
}
return 0;
}
-
AHello Hi
-
BHello Bye
-
CHi
-
DBye
-
ENo output
Answer
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");placed before thecaselabels. - Standard C
switchsemantics 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:
Evaluateswitch (1) → jump to case 1.Execute: printf("Hi");.Encounter break → exit the switch.Verification / Alternative check:Move printf("Hello"); after case 1: and before the printf("Hi");. 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 tocase 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.