I saw some surprising code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
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 run without warning. The bracket of case 1{} seems to be ignored.
myDummy(1)
-> 1
myDummy(2)
-> 2
If I modify the code for case 1 to be:
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 does not compile anymore:
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;
The brackets for case 1:{}break; do not cancel the switch context. It just creates a local scope for variable. But this is really obfuscating. Why such a behaviour?