Programming Fundamentals · Interview question

Can a case label be a variable?

A strong answer

No. Each case label must be an integer constant expression, something the compiler can fully evaluate while compiling: a literal, a #defined macro, an enum constant, sizeof, or arithmetic on those like case BASE + 1:. case x: where x is a variable is a compile error, and const int x = 5; doesn't rescue it either, because in C a const variable is still a variable, not a constant expression. (This is a genuine C/C++ difference: that same code compiles in C++.) The reason is what the compiler wants to do with the labels. Because every value is known up front, it can check that no two cases collide and then choose a strategy, a jump table when the values are dense, giving O(1) dispatch regardless of case count, or a binary search or if-chain when they're sparse. Runtime values would make all of that impossible. The practical consequences: use an enum for your case labels so you get named constants plus compiler warnings for unhandled values, reach for #define or enum when you're tempted by const, and if you truly need runtime comparison values, that's an if/else if chain or a lookup table you search yourself.

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
Can a case label be a variable? | EmbeddedPrep.io