Is there any way to break this without if/else conditionals for each layer?
#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;
}
CodePudding user response:
You can wrap the logic in a function or lambda.
Instead of break; break; break;
(which won't work) you can 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;
}
Or (same effect, different style)
#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;
}
CodePudding user response:
If you want to break
individual loop, then you can use break
in their respect loop.
Putting too many or single break
within a loop, will only break
that loop that it is within it.
#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;
}