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 ");}