C language – switch-case validation and constants: Point out the specific compile-time error(s) in this program. #include <stdio.h> int main() { int P = 10; switch (P) { case 10: printf("Case 1"); case 20: printf("Case 2"); break; case P: printf("Case 2"); break; } return 0; }
-
AError: No default value is specified
-
BError: Constant expression required at line case P:
-
CError: There is no break statement in each case.
-
DNo error will be reported.
-
ENone of the above
Answer
Correct Answer: Error: Constant expression required at line case P:
Explanation
Introduction / Context:This question checks understanding of the C switch statement rules, especially that every case label must be a constant expression known at compile time. It also probes common misconceptions such as whether a default label is mandatory and if missing break statements are compilation errors or just logic issues.
Given Data / Assumptions:
- An integer selector
Pequals 10. - Case labels include
10,20, andP. - One branch omits
breakafter printing.
Concept / Approach:In C, case labels must be constant expressions, e.g., integer literals, enums, or constexpr-like arithmetic on constants. A variable name such as P is not constant in this context. The compiler therefore issues an error for case P:. A missing default label is allowed (no error). Missing break causes fall-through at runtime but is not a compile-time error.
Step-by-Step Solution:Identify invalid label: case P: uses a non-constant variable.Recall rule: case labels must be compile-time constants.Conclude: compilation fails on the case P: line.Note: absence of default and fall-through after case 10 are legal.
Verification / Alternative check:Replace case P: by case 10: or make P an enum constant; the code will compile. Keeping default optional still compiles.
Why Other Options Are Wrong:Error: No default value is specified — a default label is optional. Error: There is no break in each case — not a compile error. No error — incorrect because of case P:.
Common Pitfalls:Using variables in case labels; assuming default is mandatory; treating missing break as a compile error rather than a logic choice.
Final Answer:Error: Constant expression required at line case P: