while循环中return、break、continue的区别

  1. return 的作用是退出循环体所在的函数,相当于结束该方法。
  2. break 的作用是结束循环,跳出循环体,执行后面的程序。
  3. continue 的作用是结束此次循环,进行下一次循环;
    下面用程序来说明:
#include<iostream>
using namespace std;
void test1(int &i)
{
  while(i--)
  {
   if(i<5)
   {
     return; //当i=4时,退出该函数
   }
  }
  i=i+1;
}
void test2(int &i)
{
  while(i--)
  {
   if(i<5)
   {
     break; //当i=4时,退出while循环,往下执行i=i+1
   }
  }
  i=i+1;
}
void test3(int &i)
{
  while(i--)
  {
   if(i<5)
   {
     continue; ///当i=4时,退出此次循环,继续执行下一次while循环
   }
  }
  i=i+1;
}
int main()
{
  int a,b,c;
  a=10;
  b=10;
  c=10;
  test1(a);
  cout<<a<<endl;  //结果为4
  test2(b);
  cout<<b<<endl;  //结果为5
  test3(c);
  cout<<c<<endl;  //结果为0
  system("pause");
  return 0;
}
发布了64 篇原创文章 · 获赞 29 · 访问量 17万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章