c++ - Why should labels in a case statement be constant? -


in javascript following statement valid.

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

but in c/c++ programming languages, when write statement, compiler gives me error showing case statement must consist of constant values. in particular circumstances writing such switch-case statements useful, c/c++ not allow me so.

now curious know point behind not allowing variable values used in case statements?

c++ has evolved c switch statements conceived jump table (branch table). implement jump tables, switch conditions should constant such can translated label.

though standard never dictates how switch statements should implemented but, importantly, case labels should such evaluated during compile time. in c , c++, switch statement evaluates expression , transfers control 1 of many case statement values evaluates value of conditional expression.

6.4.2 switch statement [stmt.switch]

the switch statement causes control transferred 1 of several statements depending on value of condition.

this behaviour makes different other languages supports, conditions in case statements.

as instance, javascript describes switch ... case statement

mdn switch

the switch statement evaluates expression, matching expression's value case clause, , executes statements associated case.

so trying compare 2 different construct , expecting behaviour same.

as answer the point behind not allowing variable values used in case statements?, had made switch .. case less efficient construct every iteration/instance, case labels should re-evaluated determine if matches conditional expression.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -