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?
Jumping past the initialization of an object, even if the object is of type
int, is always undefined behavior. Note, that theswitch-statement’s statement isn’t anything special: It is just a statement and people have [ab-]used this interesting ways, e.g., for Duff’s Device. The only thing which is special within the statement is that labels can take the formdefault:andcase <const-integer-expr>:.The statement
int i;is a definition of the variable but no initialization. Thus, no initialization of a variable is by-passed. There is no bigger problem jumping past this definition than there is in the first place. Of course, the value gets assigned when jumping tocase 1:and not when jumping tocase 2:but this is no different than what happens in code outside ofswitch-statements if people only define variables.