Hi I'm Frogatto Hi I'm Frogatto - 1 year ago 78
C Question

Why should labels in a case statement be constant?

In JavaScript the following statement is valid.

switch(true) {
case a > b:
max = a;
case a < b:
max = b;
max = a;

But in the C/C++ programming languages, when I write this statement, the compiler gives me an error showing that case statement must consist of constant values. Sometimes in particular circumstances writing such switch-case statements would be very useful, but C/C++ will not allow me to do so.

Now I am curious to know what is the point behind this to not allowing variable values to be used in case statements?

Answer Source

C++ has evolved from C where switch statements were conceived as a Jump Table (Branch Table). To implement as jump tables, the switch conditions should be constant such that it can easily be translated to a label.

Though the standard never dictates how the switch statements should be implemented but, most importantly, the case labels should be such that it could be evaluated during compile time. In C and C++, the switch statement evaluates the expression and transfers control to one of the many case statement values that evaluates to the value of the conditional expression.

6.4.2 The switch statement [stmt.switch]

The switch statement causes control to be transferred to one of several statements depending on the value of a condition.

This behaviour makes it different from other languages which supports, conditions in case statements.

As for an instance, Javascript describes switch ... case statement as

MDN switch

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.

So you are actually trying to compare two different construct and expecting the behaviour would be the same.

As to answer the point behind this to not allowing variable values to be used in case statements?, that would had made the switch .. case a less efficient construct where for every iteration/instance, the case labels should be re-evaluated to determine if it matches the conditional expression.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download