Results 1 to 18 of 18

Thread: What is the proper way to exit a nested For loop

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Jan 2008
    Posts
    11,074

    What is the proper way to exit a nested For loop

    Code:
    For y = 1 To 8
      For x = 1 To 8
        '
        '
       If Something Then ........<---- Get out of both loops
        '
        '
      Next x
    Next y
    
    '
    ' More Code
    '


    Anything I post is an example only and is not intended to be the only solution, the total solution nor the final solution to your request nor do I claim that it is. If you find it useful then it is entirely up to you to make whatever changes necessary you feel are adequate for your purposes.

  2. #2
    PowerPoster
    Join Date
    Jun 2001
    Location
    Trafalgar, IN
    Posts
    4,141

    Re: What is the proper way to exit a nested For loop

    One way would be

    y = 9
    Exit For

  3. #3
    Frenzied Member Gruff's Avatar
    Join Date
    Jan 2014
    Location
    Scappoose Oregon USA
    Posts
    1,293

    Re: What is the proper way to exit a nested For loop

    I usually use a boolean variable. If you set it to true on the innermost loop you can test for this on the outer loops and exit them as well. This is useful when many conditions can cause an exit at different points in the nest.

    One other way is to wrap your nested loops in a function and use exit function. I would only do this if the function was very short and easily understood.
    For example:
    Code:
    Private Function GridContains(Item As String) As Boolean
      Dim Row As Integer, Col As Integer
      For Row = 0 To 10000
        For Col = 0 To 10000
          If Grid(Row, Col) = Item Then
            GridContains = True
            Exit Function
          End If
        Next x
      Next y
      GridContains = False
    End Function
    Historically speaking you would be wildly unpopular with your team mates if you used this option as in most procedures it can make it a nightmare to have more than one exit point.
    Last edited by Gruff; Sep 6th, 2014 at 07:28 PM.
    Burn the land and boil the sea
    You can't take the sky from me


    ~T

  4. #4
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: What is the proper way to exit a nested For loop

    Quote Originally Posted by MarkT View Post
    One way would be

    y = 9
    Exit For
    ^^ My preference.

    Another option could be to create a Label and go there
    Code:
    ...
             If someCondition = True Then GoTo ExitLoop
         Next
    Next
    
    ExitLoop:
    ...
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  5. #5

    Thread Starter
    PowerPoster
    Join Date
    Jan 2008
    Posts
    11,074

    Re: What is the proper way to exit a nested For loop

    Quote Originally Posted by MarkT View Post
    One way would be

    y = 9
    Exit For
    I believe this will only get you out of the inner loop. I want to get out entirely


    Anything I post is an example only and is not intended to be the only solution, the total solution nor the final solution to your request nor do I claim that it is. If you find it useful then it is entirely up to you to make whatever changes necessary you feel are adequate for your purposes.

  6. #6

    Thread Starter
    PowerPoster
    Join Date
    Jan 2008
    Posts
    11,074

    Re: What is the proper way to exit a nested For loop

    Quote Originally Posted by LaVolpe View Post
    ^^ My preference.

    Another option could be to create a Label and go there
    Code:
    ...
             If someCondition = True Then GoTo ExitLoop
         Next
    Next
    
    ExitLoop:
    ...
    I was trying to avoid a GoTo


    Anything I post is an example only and is not intended to be the only solution, the total solution nor the final solution to your request nor do I claim that it is. If you find it useful then it is entirely up to you to make whatever changes necessary you feel are adequate for your purposes.

  7. #7
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: What is the proper way to exit a nested For loop

    If y=9 then the next outer loop will terminate because Y will be incremented and exceed the outer loop's iteration count

    Edited: in fact, Y can be set to any value of 8 or greater in this case.

    However, if you had code between the 2 Next statements, then simply setting Y to exceed outer loop iteration count would not be enough
    Last edited by LaVolpe; Sep 6th, 2014 at 07:01 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  8. #8

    Thread Starter
    PowerPoster
    Join Date
    Jan 2008
    Posts
    11,074

    Re: What is the proper way to exit a nested For loop

    Let me start over again

    I want to get out of the inner loop and the outer loop and there is only code in the inner loop as I showed it in my first post. I already know I can use GoTo but I would rather not and I can't set y to 9 as once out of the loop the code below is going to see where y and x are at when it exits the loop.

    I'll use GoTo if there is no other cleaner way


    Anything I post is an example only and is not intended to be the only solution, the total solution nor the final solution to your request nor do I claim that it is. If you find it useful then it is entirely up to you to make whatever changes necessary you feel are adequate for your purposes.

  9. #9
    Fanatic Member
    Join Date
    Aug 2013
    Posts
    806

    Re: What is the proper way to exit a nested For loop

    I agree with Gruff's suggestion. It's the cleanest solution, IMO, as you preserve the state of the loop variables.

    Relevant source code, stolen from Gruff and slightly modified:

    Code:
      Dim mustExitNow As Boolean
      mustExitNow = False
    
      Dim x As Long, y As Long
    
      For x = 0 To UpperBoundX
        For y = 0 To UpperBoundY
    
          If (condition required to exit) Then
            mustExitNow = True
            Exit For
          End If
    
        Next x
        
        If mustExitNow Then Exit For
    
      Next y
    Note that outside the loop, you can also test the value of mustExitNow if you want to see if the loop terminated prematurely or not.
    Check out PhotoDemon, a pro-grade photo editor written completely in VB6. (Full source available at GitHub.)

  10. #10
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: What is the proper way to exit a nested For loop

    Quote Originally Posted by jmsrickland View Post
    Let me start over again

    ...but I would rather not and I can't set y to 9 as once out of the loop the code below is going to see
    Tanner's solution is a viable one then
    Last edited by LaVolpe; Sep 6th, 2014 at 07:27 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  11. #11
    Frenzied Member
    Join Date
    Jun 2006
    Posts
    1,098

    Re: What is the proper way to exit a nested For loop

    You could use a single loop. This would be particularly useful if you would use the values x and y later to get an index (i) to an array.
    Edit: If the exit condition isn't met, the values of (x, y) will be (8, 8) rather than (9, 9) in other solutions. You would need to check the value of i after the loop.
    Code:
    For i = 0 To 63
      y = i \ 8 + 1
      x = i Mod 8 + 1
      ...
      If ... Then Exit For
    Next i
    Another solution:
    Code:
    For y = 1 To 8
     For x = 1 To 8
        ...
        If ... Then Exit For
      Next x
      If x < 9 Then Exit For ' That is, if inner loop exited without full completion
    Next y
    Last edited by Logophobic; Sep 6th, 2014 at 07:47 PM.

  12. #12

    Thread Starter
    PowerPoster
    Join Date
    Jan 2008
    Posts
    11,074

    Re: What is the proper way to exit a nested For loop

    Thanks, Logo, but I think the GoTo is much simplier.

    Too bad Exit For: Exit For doesn't work
    Last edited by jmsrickland; Sep 6th, 2014 at 07:59 PM.


    Anything I post is an example only and is not intended to be the only solution, the total solution nor the final solution to your request nor do I claim that it is. If you find it useful then it is entirely up to you to make whatever changes necessary you feel are adequate for your purposes.

  13. #13
    Frenzied Member
    Join Date
    Jun 2006
    Posts
    1,098

    Re: What is the proper way to exit a nested For loop

    Agreed, and there is certainly nothing wrong with GoTo. It is probably the most efficient solution.

  14. #14
    PowerPoster
    Join Date
    Jun 2001
    Location
    Trafalgar, IN
    Posts
    4,141

    Re: What is the proper way to exit a nested For loop

    You could also be done without a flag variable.
    Code:
    Private Sub Command1_Click()
    Dim x As Integer
    Dim y As Integer
    
        Debug.Print "Loop Start"
        
        For y = 1 To 8
            Debug.Print "y = " & y
            For x = 1 To 8
                Debug.Print vbTab & "x = " & x
                
                ' Condition to exit loop
                If y = 2 And x = 5 Then
                    Debug.Print "Exit Inner Loop"
                    Exit For
                End If
            Next x
            
            If x < 9 Then
                Debug.Print "Exit Outer Loop"
                Exit For
            End If
        Next y
        
        Debug.Print "x = " & x
        Debug.Print "y = " & y
    End Sub

  15. #15
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,219

    Re: What is the proper way to exit a nested For loop

    Quote Originally Posted by Logophobic View Post
    Agreed, and there is certainly nothing wrong with GoTo. It is probably the most efficient solution.
    +1

    ...nothing wrong with a single, direct Jump-instruction here -
    the two 'Exit For' Jump-instructions (combined with an additional If-check)
    really do look a bit "clumsy" in comparison...

    What might be considered (in case you need the state of the two loop-vars) -
    is a Function which introduces the two Vars as ByRef-parameters:

    Code:
    Function PerformLoopAndCheckSomething(x, y) As Boolean
      For x = 1 To 8: For y = 1 To 8
         '...
         If SomeCondition then Exit Function
         '...
      Next y, x
      PerformLoopAndCheckSomething = True
    End Function
    This way the Loop-Vars will keep their state - and in addition the
    Boolean-Return of the Function could be checked (when the nested loop
    got entirely through, then the result is True - whilst on early exit it is not.


    Olaf

  16. #16
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: What is the proper way to exit a nested For loop

    I with MarkT and LaVolpe! Are you trying to exit both for loops at the same time?

    Edit:

    Quote Originally Posted by Schmidt View Post
    ...nothing wrong with a single, direct Jump-instruction here -
    the two 'Exit For' Jump-instructions (combined with an additional If-check)
    really do look a bit "clumsy" in comparison...
    Yes, there is nothing wrong with using labels it is just a matter of how you use them.

    The wrong way is as substitute for a loop

    Code:
    Dim Y As integer
    Start
    
    If y = 1 then goto Start 
     y = y + 1

    There right way would be in the case of error handling or a linear approach.
    Last edited by Nightwalker83; Sep 6th, 2014 at 08:40 PM. Reason: Adding more!
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  17. #17
    Frenzied Member
    Join Date
    May 2014
    Location
    Kallithea Attikis, Greece
    Posts
    1,289

    Re: What is the proper way to exit a nested For loop

    I like as goto and the Schmidt way is very good, and not only for a next for situation but also with any kind of function that return a by reference variable. See that
    Function DoSomething(InputParam, OutputParam) as boolean
    ' do something with InputParam..

    if wrong condition then exit function
    OutParam=ValidOutPut
    DoSomething=true
    End Function


    So in a program
    we have a If statement to do something with output if function DoSomething is true...using the OutParam

    As Schmidt wrote before, we can exit from some nested for next statements when we need to do with an exit function.

  18. #18
    Addicted Member
    Join Date
    Jul 2014
    Posts
    176

    Re: What is the proper way to exit a nested For loop

    I'll go with the "GoTo <Label>" solution... It's the more efficient way.
    If I had helped you...

    Don't forget to mark your Inquiry as RESOLVED...

    I will be glad if you can also give me some Reputation points in helping you (by Clicking Rate This Post)...

    Happy VB Coding Everyone!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width