Break、continue、return用法(C++)

时间:2023-01-30 10:29:26

(1)break

直接调出当前循环体。如果是嵌套循环,他只能调出一层循环体。

Exp-1:

程序:

#include<iostream>

using namespace std;

int main()

{

    for(int i=0;i<3;i++)

    {

       cout<<"the first circle"<<"  "<<i<<endl;

       for(int j=0;j<3;j++)

       {

           if(j==1)

              break;

           cout<<"the second circle"<<"  "<<j<<endl;

       }

    }

    return 0;

}

 

运行结果:

the first circle  0

the second circle  0

the first circle  1

the second circle  0

the first circle  2

the second circle  0

请按任意键继续. . .

(2) continue

忽略循环体中continue后面的的语句,进入下一次循环开始前的条件判断,不跳出该循环。   

Exp-2:

程序:

 

#include<iostream>

using namespace std;

int main()

{

    for(int i=0;i<3;i++)

    {

       cout<<"the first circle"<<"  "<<i<<endl;

       for(int j=0;j<3;j++)

       {

           if(j==1)

              continue;

           cout<<"the second circle"<<"  "<<j<<endl;

       }

    }

    return 0;

}

 

运行结果:

the first circle  0

the second circle  0

the second circle  2

the first circle  1

the second circle  0

the second circle  2

the first circle  2

the second circle  0

the second circle  2

请按任意键继续. . .

 

(3) return

return表示中止当前函数的运行,并将操作权返回给调用者。    
如果是在main函数中,表示将操作权返回给操作系统。