goto只能在函数体内跳转,不能跳到函数体外的函数。即goto有局部作用域,需要在同一个栈内。
需要在要跳转到的程序段起始点加上标号。如下例中的part2。
1.goto 语句可用于跳出深嵌套循环
- #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;//break是跳不出多重循环的
- }
- cout<<"此处被省略"<<endl;
- part2:
- cout<<"part2"<<endl;
- system("pause");
- }
2.goto语句可以往后跳,也可以往前跳
- #include<iostream>
- using namespace std;
-
- int main()
- {
- int x,sum=0;
- //定义标号L1
- L1: cout<<"x=";
- cin>>x;
- if (x==-1)
- goto L2; //当用户输入-1时,转到L2语句处
- else
- sum+=x;
- goto L1; //只要用户没有输入-1,则转到L1语句处,程序一直将用户的输入默默地累加到变量sum中。
- //定义标号L2
- L2: cout<<"sum="<<sum<<endl;//一旦转到L2,将输出累计结果,程序运行结束。
- system("pause");
- }
3.也可以跳出switch,或者在case之间进行跳转
如:
- #include<iostream>
- using namespace std;
-
- int main()
- {
- char a;
- L1:
- cout<<"请输入一个字符"<<endl;
- cin>>a;
- 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");
- }
