c++ - gcc error when using a switch statement with a default case and a lambda function -
i not understand why code
#include <iostream> class { public: void foo(){ char g = 'm'; switch(g){ case 'g': auto f = [](){std::printf("hello world\n");}; f(); break; // default: // std::printf("go hell\n"); // break; } }; }; int main(int iargc, char *iargv[]){ a; a.foo(); }
compiles (and works) fine, whereas when uncommenting default statement
#include <iostream> class { public: void foo(){ char g = 'm'; switch(g){ case 'g': auto f = [](){std::printf("hello world\n");}; f(); break; default: std::printf("go hell\n"); break; } }; }; int main(int iargc, char *iargv[]){ a; a.foo(); }
gives me following error message
test.cpp:15:13: error: jump 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 default statement, if comment out lambda function.
i using gcc 4.8.5.
the error message tells problem is. jumping default
label goes point f
not in scope point in scope, skipping initialization.
the relevant rule standard is:
6.7 declaration statement [stmt.dcl]
it possible transfer block, not in way bypasses declarations initialization. program jumps point variable automatic storage duration not in scope point in scope ill-formed unless variable has scalar type, class type trivial default constructor , trivial destructor, cv-qualified version of 1 of these types, or array of 1 of preceding types , declared without initializer (8.6).
when have 1 case
switch there no way jump on initialization, because place can enter switch statement @ first case label, doesn't miss out initialization. if don't bypass initialization of variable there's no problem.
you don't error types double
or int
because scalar types (so if jump on initialization in scope, uninitialized). closure type created lambda not scalar type, , not declared without initializer.
Comments
Post a Comment