I've read this question about the "jump to case label" error, but I still have some questions. I'm using g++ 4.7 on Ubuntu 12.04.
This code gives an error:
int main() {
int foo = 1;
switch(foo) {
case 1:
int i = 0;
i++;
break;
case 2:
i++;
break;
}
}
The error is
jump-to-case-label.cpp: In function ‘int main()’:
jump-to-case-label.cpp:8:8: error: jump to case label [-fpermissive]
jump-to-case-label.cpp:5:9: error: crosses initialization of ‘int i’
However, this code compiles fine,
int main() {
int foo = 1;
switch(foo) {
case 1:
int i;
i = 0;
i++;
break;
case 2:
i++;
break;
}
}
Is the second code any less dangerous than the first? I'm confused as to why g++ allows it.
Secondly, the fix for this problem is to scope the initialized variable. If the initialized variable is a large object, and the switch statement is in a while loop, won't the constructor and destructor be called each time that scope is entered and left, causing a decrease in efficiency? Or will the compiler optimize this away?