c++中goto语句用法

goto只能在函数体内跳转,不能跳到函数体外的函数。即goto有局部作用域,需要在同一个栈内。

需要在要跳转到的程序段起始点加上标号。如下例中的part2。

1.goto 语句可用于跳出深嵌套循环


  
  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. for( int i= 0;i< 10;i++)
  6. for( int j= 0;j< 10;j++)
  7. for( int k= 0;k< 10;k++)
  8. {
  9. cout<<i*j*k<< " ";
  10. if( 216==i*j*k)
  11. goto part2; //break是跳不出多重循环的
  12. }
  13. cout<< "此处被省略"<< endl;
  14. part2:
  15. cout<< "part2"<< endl;
  16. system( "pause");
  17. }

2.goto语句可以往后跳,也可以往前跳


  
  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int x,sum= 0;
  6. //定义标号L1
  7. L1: cout<< "x=";
  8. cin>>x;
  9. if (x== -1)
  10. goto L2; //当用户输入-1时,转到L2语句处
  11. else
  12. sum+=x;
  13. goto L1; //只要用户没有输入-1,则转到L1语句处,程序一直将用户的输入默默地累加到变量sum中。
  14. //定义标号L2
  15. L2: cout<< "sum="<<sum<< endl; //一旦转到L2,将输出累计结果,程序运行结束。
  16. system( "pause");
  17. }

3.也可以跳出switch,或者在case之间进行跳转

如:


  
  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. char a;
  6. L1:
  7. cout<< "请输入一个字符"<< endl;
  8. cin>>a;
  9. switch(a)
  10. {
  11. case 'a':
  12. cout<< "case a"<< endl;
  13. goto L1;
  14. //break;
  15. L2:
  16. case 'b':
  17. cout<< "case b"<< endl;
  18. break;
  19. case 'c':
  20. cout<< "case c"<< endl;
  21. // break;
  22. goto L2;
  23. default:
  24. break;
  25. }
  26. system( "pause");
  27. }


猜你喜欢

转载自blog.csdn.net/monk1992/article/details/83615339