Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc error when using a switch statement with a default case and a lambda function

I do not understand why this code

#include <iostream>

class A {
    public:


    void foo(){
        char g = 'm';
        switch(g){
            case 'g':
                auto f = [](){std::printf("hello world\n");};
                f();
                break;
//            default:
//                std::printf("go to hell\n");
//                break;
        }
    };
};



int main(int iargc, char *iargv[]){
    A a;
    a.foo();
}

compiles (and works) fine, whereas when uncommenting the default statement

#include <iostream>

class A {
    public:


    void foo(){
        char g = 'm';
        switch(g){
            case 'g':
                auto f = [](){std::printf("hello world\n");};
                f();
                break;
            default:
                std::printf("go to hell\n");
                break;
        }
    };
};



int main(int iargc, char *iargv[]){
    A a;
    a.foo();
}

gives me the following error message

test.cpp:15:13: error: jump to case label [-fpermissive]
         default:
         ^
test.cpp:12:22: error:   crosses initialization of ‘A::foo()::__lambda0 f’
             auto f = [](){std::printf("hello world\n");};

I can use a default statement, if I comment out the lambda function.

I am using gcc 4.8.5.

like image 763
Mohammed Li Avatar asked Dec 04 '22 23:12

Mohammed Li


1 Answers

You need to enclose your case 'g' body in braces. This is not because of the lambda per se, but due to the creation of any new variable in a case statement.

Without the default I suppose it doesn't complain because there's only one place the execution can flow. But with default and no braces, you have a problem because the scope of f extends to the default code but it won't be initialized there.

like image 168
John Zwinck Avatar answered Feb 23 '23 00:02

John Zwinck