Difficulty: Easy
Correct Answer: 1, 3, and 4
Explanation:
Introduction / Context:
Understanding when to use switch and how compilers may optimize it is foundational in C. Also important is recognizing fall-through and the role of break statements.
Given Data / Assumptions:
Concept / Approach:
(1) True: switch shines when matching exact discrete values. (2) False in portable C: ranges require if-else chains unless you manually enumerate each value. (3) True in many implementations: compilers may create jump tables, binary searches, or chains depending on density—behavior is not guaranteed but is common. (4) True: break is not required; omitting it enables intentional fall-through, although you must manage control flow carefully.
Step-by-Step Solution:
Choose switch for enums or clustered integers.Use if-else for ranges (e.g., 0 <= x < 10, etc.).Insert break to avoid unintended fall-through unless fall-through is desired and documented.
Verification / Alternative check:
Examine -O2 disassembly for dense case sets to see jump-table generation; sparse sets often compile into comparisons.
Why Other Options Are Wrong:
Any option including (2) claims suitability for ranges, which is misleading. Options omitting (3) or (4) miss real-world compiler behavior and C control-flow rules.
Common Pitfalls:
Forgetting break; assuming jump-table generation is guaranteed; attempting case ranges without compiler extensions.
Final Answer:
1, 3, and 4
Discussion & Comments