C switch with computed case labels: Identify whether this program is valid and if any error exists when case uses an arithmetic expression. #include <stdio.h> int main() { int i = 1; switch (i) { case 1: printf("Case1"); break; case 12+4: printf("Case2"); break; } return 0; }

Difficulty: Easy

Correct Answer: No Error

Explanation:


Introduction / Context:
This question verifies that you know case labels can be integer constant expressions, not just simple literals. It also checks the misconception that a default label is mandatory.


Given Data / Assumptions:

  • i equals 1, so case 1 matches.
  • A second label is 12+4, which equals 6.
  • No default case is present.


Concept / Approach:
C allows case labels to be integer constant expressions; the compiler evaluates them at compile time. As long as values are unique, there is no error. There is also no requirement for a default case. Therefore, this program compiles and runs; it prints “Case1”.


Step-by-Step Solution:
Compute 12+4 → 6; distinct from 1 → no duplication.Switch on 1 transfers to case 1.Prints “Case1” then breaks; program ends normally.


Verification / Alternative check:
Try replacing the computed case with 1 or another expression evaluating to 1; the compiler will then report duplicate case label.


Why Other Options Are Wrong:
Error in case 1*2+4 — wrong, it’s a valid constant expression. No default specified — optional. Error in switch — none exists here.


Common Pitfalls:
Believing only literals are permitted; forgetting that duplicates (not expressions) cause errors.


Final Answer:
No Error

More Questions from Control Instructions

Discussion & Comments

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