Why can't we use variables inside a case in switch construct?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • radha gogia
    New Member
    • Feb 2015
    • 56

    Why can't we use variables inside a case in switch construct?

    If I have an integer variable like int a=9 then in the switch case If i write
    switch(a)
    {
    case 4+a: printf("hii");

    }

    then why is this statement a compile-time error that variables cannot be used inside a case statement why does the compiler not subtitutes the values in place of the variables.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The compiler needs to know which case you want before your program runs or the correct code cannot be generated. So case 4+a is an error because the program needs to be running when a is evaluated.

    The switch cases need to be symbolic like 4 or 'A'.

    Comment

    Working...