Programming Fundamentals · Interview question

When should you prefer switch over an if/else if chain?

A strong answer

When you're comparing a single integer (or char/enum) value against a list of constants. switch makes that intent explicit at a glance, the reader immediately sees "this is dispatching on one value", and it avoids the visual noise of repeating cmd == 'a', cmd == 'b', etc. For larger case counts, the compiler can also generate a jump table instead of a linear chain of comparisons, giving O(1) dispatch. Stick with if/else if when conditions involve ranges, multiple variables, strings, or non-equality tests, switch can't handle those.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

The switch Statement

When an if/else chain compares one value against many constants, switch is shorter, faster, and tells the reader exactly what's happening.

More The switch Statement questions

Browse all 472 interview questions