有没有任何方法可以打破这一点,而不对每一层的if/else条件?
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
break; break; break;
}
}
}
cout << "END";
return 0;
}发布于 2022-09-02 01:36:03
您可以将逻辑封装在函数或lambda中。
而不是break; break; break; (这是行不通的),您可以return;。
#include <iostream>
using namespace std;
int main()
{
auto nested_loops = []
{
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
// Done with all the looping
return;
}
}
}
};
nested_loops();
cout << "END";
return 0;
}或(相同的效果,不同的风格)
#include <iostream>
using namespace std;
int main()
{
[] {
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
// Done with all the looping
return;
}
}
}
} ();
cout << "END";
return 0;
}发布于 2022-09-02 02:05:26
如果您想要break单独的循环,那么您可以在循环中使用break。
将过多的或单个break放入循环中,只会使break的循环知道它在其中。
#include <iostream>
using namespace std;
int main()
{
[] {
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
break;
}
break;
}
break;
}
} ();
cout << "END";
return 0;
}发布于 2022-09-24 04:58:16
为了打破嵌套循环,您可以使用goto语句。
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
goto break_outer_loop;
}
}
}
break_outer_loop:
cout << "END";
return 0;
}注意,通常应该避免使用goto。但是,为了突破嵌套循环,it is generally considered acceptable。
https://stackoverflow.com/questions/73576943
复制相似问题