How To Exit from loop with out resrarting app

I have outer while loop and inner while loop
Sometimes I Need To Exit from while loop when nessesary loop conditions is not met
How can I proceed?

Factor out both loops into a function, then return from the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void foo()
{
    while (true)
    {
        while (true)
        {
            if (true)
            {
                return;
            }
        }
    }
}

int main()
{
    foo();
}


Alternatively, use goto. *grabs popcorn*
Last edited on
Break exits from the innermost loop.
so
1
2
3
4
5
6
7
8
while(cond)
{
   while(cond2)
    {
      if(bad)
          break; //stops this while loop, resumes outer while loop. 
    }
}


that concept can be paired with conditionals:
1
2
3
4
5
6
7
8
9
10
11
while(cond && didbreak) //won't resume, because you set the bool below
{
   while(cond2)
    {
      if(didbreak = bad) //bad can be a bool expression
         {
          break; //stops this while loop, resumes outer while loop. 
         }
    }
     if(didbreak) continue; //if there is more code after the inner while loop. 
}


this gets kind of hairy beyond 3 or so nested loops. if you are really, really deep, goto is a fine option: every other option requires more lines of code and twisting to get to the same place.
1
2
3
4
5
6
7
8
9
while(first)
  while(second)
    while(third)
      while(forth)
       {
           if(bigproblem)
            goto getout;
       }
getout: ;


I believe you can also rig error handling to get out, if you want to slightly misuse the concept. error handling is a powerful hack that is frowned upon for use outside of actual error handling, but it CAN be used for things like this or other weird constructs to avoid tying yourself into a knot to express your idea. Here is an example of it https://cplusplus.com/forum/lounge/154085/. As noted there, misuse of error handling is both inefficient as well as questionable design/style/approach.


often nested loops are just handy but not necessary, for example iterating over a multi-d array. if you re-rig it for 1d single loop, its easier to get out of there, and its often trivial to do that.
Last edited on
Whouaaaa! Goto :)
In a deep case, it's true - goto could be interesting, but prefer break/continue for inner loops with multiple conditions ++
https://cplusplus.com/forum/beginner/284650/


Last edited on
is there a way to leave loop if can not meet break/continue conditions?
Maybe on button click or key input (cin)?
Input, when handled, stores data somewhere. That data can be used in condition.

If the loop does not handle the input, then something else must do it asynchronously.
Topic archived. No new replies allowed.