The example is as follows:
1,
//: c06: nojump. CPP <br/> // from thinking in C ++, 2nd Edition <br/> // available at http://www.BruceEckel.com <br/> // (c) bruce Eckel 2000 <br/> // copyright notice in copyright.txt <br/> // can't jump past constructors <br/> Class X {<br/> public: <br/> X (); <br/>}; <br/> X: X () {}< br/> void F (int I) {<br/> if (I <10) {<br/> // goto jump1 ;/ /Error: goto bypasses init <br/>}< br/> X x1; // constructor called here <br/> jump1: <br/> switch (I) {<br/> case 1: <br/> X X2; // constructor called here <br/> break; <br/> // Case 2: // error: case bypasses init <br/> X X3; // constructor called here <br/> break; <br/>}< br/> int main () {<br/> F (9); <br/> F (11); <br/> }///:~ <Br/>
During compilation, it is correct to annotate the two lines in the figure and compile them. After removing the comments from Goto, the following error is returned:
That is, skip the X1 initialization, comment out the X1 initialization statement, and pass
The problem occurs after the comment of the second case is opened, and the following error is returned:
The prompt is a problem.
2,
The magic is that the X2 initialization statement or case2 can be compiled through
Switch (I) <br/>{< br/> case 1: <br/> // X X2; // constructor called here <br/> break; <br/> case 2: // error: Case bypasses init <br/> X X3; // constructor called here <br/> break; <br/>}
3. Correct
Then, we modifyCodeAs follows:
Void F (int I) <br/>{< br/> if (I <10) <br/>{< br/> goto jump1; // error: goto bypasses init <br/>}< br/> // X x1; // constructor called here <br/> jump1: <br/> switch (I) <br/>{< br/> case 1: <br/>{< br/> X X2; // constructor called here <br/> break; <br/>}< br/> case 2: // error: Case bypasses init <br/>{< br/> X X3; // constructor called here <br/> break; <br/>}< br/>}
Through compilation
Conclusion: The main problems are:
1. the compiler checks whether the object definition is placed in a condition block, such as switch and goto. The first one is goto or switch and skips the X1 definition.
2. For the switch.When a switch statement defines a variable, if it is not in a statement block, its scope ends until "}" of the switch is met, the case statement may skip defining its entire scope.
Therefore, add parentheses to the definition so that it can end the scope at the end of case }.
Http://hi.baidu.com/ati_crossfire/blog/item/e2bb6b10023119d6a6ef3f32.html
Backup retention