goto只能在函数体内跳转,不能跳到函数体外的函数。即goto有局部作用域,需要在同一个栈内。
需要在要跳转到的程序段起始点加上标号。如下例中的part2。
1.goto 语句可用于跳出深嵌套循环
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#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语句可以往后跳,也可以往前跳
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18#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之间进行跳转
如:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29#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"); }

最后
以上就是神勇秀发最近收集整理的关于c++中goto语句用法的全部内容,更多相关c++中goto语句用法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复