C switch-case constants and duplicates:
Which compilation error(s) will be reported for this switch that includes a computed case and a literal with the same value?
#include
int main()
{
int a = 5;
switch (a)
{
case 1:
printf("First");
case 2:
printf("Second");
case 3 + 2:
printf("Third");
case 5:
printf("Final");
break;
}
return 0;
}
-
AThere is no break statement in each case.
-
BExpression as in case 3 + 2 is not allowed.
-
CDuplicate case case 5:
-
DNo error will be reported.
-
ENone of the above
Answer
Correct Answer: Duplicate case case 5:
Explanation
Introduction / Context:This question focuses on constant expressions in case labels and the prohibition of duplicate case values. It also checks the misconception that every case must end with a break to compile.
Given Data / Assumptions:
- A case uses
3 + 2. - Another case uses the literal
5. - Several cases have no
break.
Concept / Approach:Case labels must be integer constant expressions, and duplicates are illegal. The expression 3 + 2 is a constant expression that evaluates to 5 at compile time, colliding with the later case 5:. Missing break may cause fall-through, but that is a runtime behavior choice, not a compile error.
Step-by-Step Solution:Evaluate 3 + 2 → 5.Detect duplicate labels: case 3 + 2 and case 5 both equal 5.Compiler emits duplicate case label error.
Verification / Alternative check:Replace one of the labels with a distinct constant (e.g., 6) and compilation succeeds, regardless of missing break statements.
Why Other Options Are Wrong:Expression not allowed — constant expressions are allowed. No break in each case — not a compile error. No error — incorrect due to duplication.
Common Pitfalls:Forgetting that constant expressions are folded at compile time; believing break is mandatory.
Final Answer:Duplicate case case 5: