3

I've already read this " Why can't variables be declared in a switch statement? ".

However, I still can't understand why does this work:

switch(n){
case VAL:
    int a;
    ...
    break;
case OTHER_VAL:
    a = 12
    ...
    break;
}

suppose to this:

switch(n){
case VAL:
    int a = 12;
    ...
    break;
case OTHER_VAL:
    ...
    break;
}

I understand that that initialization part is bypassed, at the label val, so why does the declaration part isn't?.

0_NULL
  • 73
  • 1
  • 7
  • Because of the reason given by the compiler: 'initialization of 'newVal' is skipped by 'case' label'. When you remove the initialization, there is nothing to be skipped. – user207421 Oct 27 '20 at 04:47
  • @MarquisofLorne Did you close the question? Because the question linked doesn't actually answer this question – Ilan Keshet Oct 27 '20 at 04:49
  • @IlanKeshet The 2nd answer to the linked question answers it in great detail. – Eugene Oct 27 '20 at 04:51
  • @MarquisofLorne I kinda still don't get it. If the switch statement jumps to a `case`, doesn't the statement inside of other `cases` didn't run? or maybe I just don't understand the jumping thing they talk about? – 0_NULL Oct 27 '20 at 04:53
  • @RenzAguirre Switch Statements are basically jump tables. IE some way to access functionality with a given key – Ilan Keshet Oct 27 '20 at 04:56
  • @IlanKeshet so does the declaration of `a` is skipped like the initialization part also?, because the 2nd answer in the link question, at the comment says, that it skips it. However, if it skips it, why can we use it?, or it will be an undefined behavior? – 0_NULL Oct 27 '20 at 05:13
  • @RenzAguirre I'm going to be honest with you. I've been programming for more than 16 years now, and it's difficult for me the understand too :) – Ilan Keshet Oct 27 '20 at 05:18
  • @RenzAguirre I've always addressed this issue by braces... but the stuff in that post is new to me... – Ilan Keshet Oct 27 '20 at 05:20
  • @IlanKeshet, I see, since this is already a close question, I'll just try to research more about it. Thanks. – 0_NULL Oct 27 '20 at 05:30

0 Answers0