Usage of the GOTO statement in C ++

Source: Internet
Author: User

Goto can only jump to the function body, but not to the function in vitro. That is, Goto has a local scope and needs to be in the same stack.

To jumpProgramSegment start point plus the label. Part2 in the following example.

1. The GOTO statement can be used to jump out of a deep nested loop.

 
# Include <iostream> using namespace STD; int main () {for (INT I = 0; I <10; I ++) for (Int J = 0; j <10; j ++) for (int K = 0; k <10; k ++) {cout <I * j * k <""; if (216 = I * j * k) goto Part2; // The break cannot skip multiple cycles} cout <"omitted here" <Endl; Part2: cout <"Part2" <Endl; System ("pause ");}

2. The GOTO statement can jump back or forward.

# Include <iostream> using namespace STD; int main () {int X, sum = 0; // defines the label l1l1: cout <"x ="; CIN> X; if (x =-1) goto L2; // when the user inputs-1, go to the L2 statement else sum + = x; goto L1; // if the user does not enter-1, it is transferred to the L1 statement, and the program accumulates the user input to the sum variable silently. // Define the label l2l2: cout <"sum =" <sum <Endl; // once switched to L2, the accumulative result is output and the program running ends. System ("pause ");}

3. You can also jump out of the switch or jump between cases.

For example:

# Include <iostream> using namespace STD; int main () {char a; L1: cout <"enter a character" <Endl; CIN>; switch (a) {Case 'A': cout <"case a" <Endl; goto L1; // break; L2: Case 'B ': cout <"case B" <Endl; break; Case 'C': cout <"Case C" <Endl; // break; goto L2; default: break;} system ("pause ");}

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.