Programming Fundamentals · Interview question

What should you put in the default case, and is it always required?

A strong answer

default is optional, a switch with no default simply does nothing when no case matches. But it's almost always worth including, even when you've covered every "valid" value. For enum switches, putting default: assert(0 && "unhandled enum value"); (or logging) catches the inevitable case where someone adds a new enum value and forgets to extend the switch. For input-driven switches, default is your error path. The exception is small, exhaustive switches where the compiler can warn about missing cases (some compilers do this for enum switches without a default).

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