打破for循环
问题描述:
我知道我必须使用break才能退出for循环.
但是,如果彼此之间有多个循环,那么如何退出所有循环?
您必须在每个for循环的末尾使用break还是我可以只使用一个break退出所有循环?
即
Hi,
I know I have to use break to exit from a for loop.
But if you have several loops within eachother then how do you exit all of the loops?
Do you have to use break at the end of each for loop or can I just use one break to exit all loops?
i.e.
for (condition)
{
for(condition)
{
for(condition)
{
if (myBoolean == false)
{
break;
}
}
}
}
答
这取决于您是否总是打破所有循环的逻辑,但是您将需要实现一些逻辑以打破循环.
根据您的逻辑,您可能需要多个变量,但这显示了基本原理
It will depend on your logic of whether you would always break out all the loops, but you are going to need to implement some logic to break out of the loops.
You may need more than one variable depending on your logic, but this shows the basic principle
bool breakAll = false;
for (condition1)
{
for(condition2)
{
for(condition3)
{
if (myBoolean == false)
{
breakAll = true;
break; // breaks condition3 for loop
}
}
if (breakAll)
{
break; // breaks condition2 for loop
}
}
if (breakAll)
{
break; // breaks condition1 for loop
}
}
break
statemnet只会从 current 循环中退出-没有机制可以从所有循环中退出.我可能会将它们编码为一个方法,并改为使用return
.有些纯粹主义者会告诉我们,多个出口点是撒但的产物.
如果您不能使用return
,那么这是可以证明goto
合理的少数情况之一.
Abreak
statemnet will only exit from the current loop - there is no mechanism to exit from all loops. I would probably code them into a method, and use areturn
instead. There are purists who will tell that multiple exit points are the spawn of Satan however.
If you can''t usereturn
than this is one of the very, very few occaisions when agoto
can be justified.
您不能使用break
离开嵌套循环.
您可以使用goto
或将代码放入函数中,然后使用return
删除该代码.
You cannot usebreak
to get out of nested loops.
You could either use agoto
or place the code in a function and use areturn
to get out of it.