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

后端 未结 23 2972
一生所求
一生所求 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 06:09

    It appears that anonymous objects can be declared or created in a switch case statement for the reason that they cannot be referenced and as such cannot fall through to the next case. Consider this example compiles on GCC 4.5.3 and Visual Studio 2008 (might be a compliance issue tho' so experts please weigh in)

    #include 
    
    struct Foo{};
    
    int main()
    {
        int i = 42;
    
        switch( i )
        {
        case 42:
            Foo();  // Apparently valid
            break;
    
        default:
            break;
        }
        return EXIT_SUCCESS;
    }
    

提交回复
热议问题