在没有goto的情况下退出嵌套循环
exiting from nested loop without goto
如何在没有goto的情况下退出嵌套while()或for()?
例如,如果我在一个函数中使用如下三个循环:
void myfun(){
for (;;)
{
while( true )
{
for (;;)
{
//what is the exit code of all loop() from here?
}
}
}
}
使用break;
只能退出一个循环,
但是我怎样才能退出所有循环呢
循环可以由计数器限制或不受限制。
我个人会重写代码,这样一来就不会有嵌套循环。类似这样的东西:
bool myFun2
{
for (;;)
{
if(something) return true;
}
// If the loop isn't "forever", return false here?
}
bool myFun1()
{
while( true )
{
if (myFun2()) return true;
}
// return false here if needed.
}
void myfun()
{
for (;;)
{
if(myFun1()) break;
}
}
例如,这比试图找出某个exitLoop
变量设置的条件要容易得多。
不能,您需要在while
上下文中再次中断,或者使用变量作为退出标志来更改循环:
bool exit = false;
for (;;){
while (!exit){
for (;;){
exit = true;
break;
}
}
if (exit) break;
}
你的代码中有多少循环就有多少循环
如果您想跳出离开函数的function
,那么您应该使用return
。然而,如果你只想跳出嵌套的循环&不出功能,则可以throw an exception
。这种方法将帮助您避免像一些人所做的那样将代码分解为几个functions
。然而CCD_ 8是为图书馆设计者设计的;我们应该避免过度使用它们。就我个人而言,使用goto
在这种情况下是最好的,但正如你所要求的那样,因此我这么说。那么你的代码将是这样的:-
void myfun()
{
try
{
for (;;)
{
while( true )
{
for (;;)
{
if (/*some condition*/)
throw false;
}
}
}
}
catch (bool)
{
cout<<"caught";
}
// do stuffs if your code is successful that is you don't break out
}
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在不返回 C++ 值的情况下退出 int 函数?
- 程序在没有输入的情况下退出,它有基本的,驱动的类属性初始化问题
- 如何在不退出和失去断点的情况下重新加载重新编译的二进制文件
- 为什么GetMessage在不发送任何消息的情况下退出我的程序
- 在另一个线程正在运行的情况下退出应用程序时出错
- getchar 有什么问题(因为程序在没有检查的情况下退出循环)
- 多线程服务器在不等待客户端连接的情况下退出
- 在没有goto的情况下退出嵌套循环
- 在没有c++11的情况下,使用boost标记线程退出的正确方法是什么
- 在不使用pkill的情况下优雅地退出程序的最佳方式
- 从vi运行各种c或cpp开发任务"就像在不退出vi的情况下运行cpp程序一样。
- 如何在没有输入的情况下退出c++程序