- return 的作用是退出循環體所在的函數,相當於結束該方法。
- break 的作用是結束循環,跳出循環體,執行後面的程序。
- 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;
}