C++ multiple loops break
  |   Source

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.

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

Comments powered by Disqus