Reputation: 59
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;
}
Upvotes: 1
Views: 1267
Reputation: 24726
In order to break out of a nested loop, you can use the goto
statement.
#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;
}
Note that goto
should generally be avoided. However, for breaking out of a nested loop, it is generally considered acceptable.
Upvotes: 0
Reputation: 144
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;
}
Upvotes: 0
Reputation: 63725
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;
}
Upvotes: 3