是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
当前回答
break语句终止它出现的最近的封闭do、for、switch或while语句的执行。控制权转移到终止语句后面的语句。
从msdn。
其他回答
我知道这是老帖子了。但我想提出一个更合理、更简单的答案。
for(unsigned int i=0; i < 50; i++)
{
for(unsigned int j=0; j < conditionj; j++)
{
for(unsigned int k=0; k< conditionk ; k++)
{
// If condition is true
j= conditionj;
break;
}
}
}
虽然这个答案已经提出了,但我认为一个很好的方法是这样做:
for(unsigned int z = 0; z < z_max; z++)
{
bool gotoMainLoop = false;
for(unsigned int y = 0; y < y_max && !gotoMainLoop; y++)
{
for(unsigned int x = 0; x < x_max && !gotoMainLoop; x++)
{
//do your stuff
if(condition)
gotoMainLoop = true;
}
}
}
Goto对于打破嵌套循环非常有用
for (i = 0; i < 1000; i++) {
for (j = 0; j < 1000; j++) {
for (k = 0; k < 1000; k++) {
for (l = 0; l < 1000; l++){
....
if (condition)
goto break_me_here;
....
}
}
}
}
break_me_here:
// Statements to be executed after code breaks at if condition
break语句终止它出现的最近的封闭do、for、switch或while语句的执行。控制权转移到终止语句后面的语句。
从msdn。
打破嵌套循环的另一种方法是将两个循环分解成一个单独的函数,并在希望退出时从该函数返回。
当然,这也引发了另一个争论,即是否应该显式地从函数的任何地方返回,而不是在函数的末尾。