The variable definition inside the switch:
1 inti =1;2 Switch. IO3 {4 Case 0:5 stringStr//Error6 intVal1 =0;//Error7 intVal2;// Right8 intVal3; Val3 =0;// Right9 Case 1:TenVal2 =9; Onecout << Val2 <<Endl; A}
C + + Primer P163: If a variable with an initial value is somewhere outside the scope and the variable is in scope at another location, then the behavior of jumping from one place to the next is illegal.
In the above code line 5, 6 is wrong, line 7, 8 is no problem.
The first thing to be clear is that for variables in line 5, 6, 7, 8, the scope after the declaration within the {} of the entire switch statement is visible. Case statements do not constitute a separate scope, that is, the val2 defined under case 0: is also visible under cases 1 (the red font appears to be problematic).
However, Line5, 6 is wrong, because the variables are initialized when the variables are declared in rows 5 and 62 (line 5 calls the default initializer), and if this code is skipped, the compiler can make an unexpected error. Line 7, 8 is correct, because the variable is not initialized at the time of declaration.
Therefore, you cannot skip a variable with an initial value (within the same scope). In the goto statement, the same:
1 inti =1;2 Gotocase_1;3 4 Case_0:5 intVal1;// Right6 intVal2 =9;//Error7 case_1:8Val1 =9;9Val2 =Ten;
test_scope.cpp:In function 'int main (intChar* *) ': Test_scope.cpp:7: Error: Jump-to-label ' Case_1 ' test_scope.cpp:2: Error: From heretest_scope.cpp:6: Error: (skipped the initialization of the Val2)
Variable declarations in a switch statement in C + + and