gpt4 book ai didi

c++ - 不使用 goto 退出嵌套循环

转载 作者:太空狗 更新时间:2023-10-29 20:56:16 26 4
gpt4 key购买 nike

如何在不使用 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 变量设置了哪些条件要容易得多。

关于c++ - 不使用 goto 退出嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33981835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com