Programming Fundamentals · Interview question

Why can't you switch on a string in C?

A strong answer

Two reasons. First, switch is defined to dispatch on an integral value via equality of bit patterns, its case labels are compile-time integer constants, and string literals are pointers, not integers. Second, string equality in C means comparing characters with strcmp, not comparing pointer values, so a hypothetical case "Ada": would have to invoke a function at run time, which conflicts with the constant-time, constant-comparison model of switch. The standard workaround is an if (strcmp(...) == 0) ... else if (strcmp(...) == 0) ... chain, or map the strings to an enum first and then switch on the enum.

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