I saw an unexpected code:
#include <iostream>
using namespace std;
int main() {
auto myDummy = [](int i){
switch(i){
case 0: return 0;
case 1:{
std::cout << "Evaluated 1\n";
if(i == 1){
return 1;
}
case 2:
std::cout << "Evaluated 2\n";
return 2;
}
break;
default: return -1;
}
};
std::cout << myDummy(1) << "\n";
return 0;
}
It compiles and runs without warning. The bracket of case 1 {} seems to be ignored.
myDummy (1)
-> 1
myDummy (2)
-> 2
If I change the code for case 1 as follows:
case 1:{
std::cout << "Evaluated 1\n";
int a = i;
if(a == 1){
return 1;
}
case 2:
std::cout << "Evaluated 2\n";
return 2;
}
break;
then it no longer compiles:
prog.cpp: 16: 13: error: jump to case label [-fpermissive]
case 2:
^ prog.cpp:12:21: note: crosses initialization of 'int a'
int a = i;
Brackets for case 1: {} break; will not undo the switch context. It just creates a local scope for the variable. But this is really confusing. Why is this behavior?
source
share