Search code examples
c++break

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;
}

Solution

  • 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;
    }