Why can't variables be declared in a switch statement?

后端 未结 23 2982
一生所求
一生所求 2020-11-21 05:15

I\'ve always wondered this - why can\'t you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring

23条回答
  •  感动是毒
    2020-11-21 05:49

    Interesting that this is fine:

    switch (i)  
    {  
    case 0:  
        int j;  
        j = 7;  
        break;  
    
    case 1:  
        break;
    }
    

    ... but this isn't:

    switch (i)  
    {  
    case 0:  
        int j = 7;  
        break;  
    
    case 1:  
        break;
    }
    

    I get that a fix is simple enough, but I'm not understanding yet why the first example doesn't bother the compiler. As was mentioned earlier (2 years earlier hehe), declaration is not what causes the error, even despite the logic. Initialisation is the problem. If the variable is initialised and declared on the different lines, it compiles.

提交回复
热议问题