2

I have some code that uses label, an example of it is below:

SUB occupy (x)
occupied(x) = 0
FOR i = 1 TO 40
IF armyloc(i) = x THEN 
    occupied(x) = i
    GOTO holdup
ELSE
END IF
NEXT i
holdup:
END SUB

As you can see, it uses the label holdup to jump out of the For..Next loop it is in. I don't know a good way to change this to be better/proper code? For example, I might usually do something like this:

SUB occupy (x)
occupied(x) = 0
FOR i = 1 TO 40
IF armyloc(i) = x THEN 
    occupied(x) = i
    GOTO holdup
ELSE
       NEXT i
END IF
END SUB

But this creates a problem - the FOR..NEXT loop is now nested within an IF..THEN for half of it. Any suggestions on ways to resolve this issue?

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
  • 3
    EXIT FOR? I don't know Basic, but it comes up in the documentation http://msdn.microsoft.com/en-us/library/zxkf5z4b%28v=vs.71%29.aspx – nhahtdh Oct 20 '12 at 04:01
  • I think you may be right...but I haven't been able to find an example that shows the actual usage of the EXIT FOR. e.g., this link says to do it - but doesn't show what it exactly looks like when done. – Dave Mackey Oct 20 '12 at 04:05
  • 2
    This one gives an example: http://msdn.microsoft.com/en-us/library/t2at9t47%28v=vs.80%29.aspx – nhahtdh Oct 20 '12 at 04:06
  • 3
    Unfortunatly I do not have a computer with VB6 fired up right now, but I beleive that an `Exit For` anywhere in the body of the statement will cause the loop to exit. Just Replace the `GOTO` statement with `Exit For` – Mark Hall Oct 20 '12 at 04:31

2 Answers2

1

As Mark Hall noted in the comments above, using Exit For works well in these situations. Remove the GOTO and replace with an Exit For statement.

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
0
SUB occupy (x)
occupied(x) = 0
FOR i = 1 TO 40
    IF armyloc(i) = x THEN occupied(x) = i: Exit For
NEXT i
END SUB
GaryNg
  • 1,103
  • 9
  • 16