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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With