user19816087
user19816087

Reputation: 59

How to break out of a nested loop?

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

Answers (3)

Andreas Wenzel
Andreas Wenzel

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

Jitu DeRaps
Jitu DeRaps

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

Drew Dormann
Drew Dormann

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

Related Questions