Variable declarations in a switch statement in C + + and

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.