Gcc when using switch statement with default case and 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) perfectly, while when uncommenting the default instructions

#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 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 the default instruction if I comment on the lambda function.

I am using gcc 4.8.5.

+4
source share
4 answers

The error message tells you what the problem is. The transition to the label defaultoccurs from the point where fit is not in scope to the point where it is in scope, skipping its initialization.

The relevant standard rule:

6.7 [stmt.dcl]

, , . , , , , , , , cv- (8.6).

case , , , switch, - , . , .

double int, (, , , ). , , .

+6

case 'g' . - , - case.

, , , . , f default, .

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

A switch . , switch.

(N4296 §6.7/3) ( ):

[] , , . , , , , , , ,, , .

, default, f ( ), .

+3
source

wrap your code between braces or read it in the same block.

The default jump skips variable declaration.

case 'g':
    {
                auto f = [](){std::printf("hello world\n");};
                f();
                break;
    }
0
source

Source: https://habr.com/ru/post/1654433/


All Articles