.. title: C++ multiple loops break
.. slug: c++-multiple-loops-break
.. date: 2024-05-24 13:29:53 UTC+02:00
.. tags: 
.. category: Programming
.. link: 
.. description: 
.. type: text

Ok, another post of the line "so I know where to look when I will need it".

Recently I had the problem to exit from a nested loop in C++, keeping the right value. A simple ``break;`` steatement
in the inner loop of course did not work since it exit only its loop, but I needed to exit even the external one.

So after looking around a little, I came up with a solution based on Lambda.

.. code:: 

    for (int pos = 0; pos < limit; pos++) {
        [&] {
            for (int y = 0; y < limit; y++) {
                for (int pos = 0; pos < limit; pos++) {
                    if (_condition_) {
                        varToKeep = y;
                        return;
                    }
                }
            }
        }();
        do something with varToKeep;
        
    }

This whay the execution end for the 2 inner ``for`` loops once the condition is true and in the outer ``for`` loop
I can do whatever I need.

Of course it is not something new I come up with, just a variation of something found on Internet.
