Goto in For-loop

miklquick

Member
Licensed User
Dear professionals,

I have a for-loop in which under certain conditions it should skip part of the code and jump to the next increment (Next i). e.g.:

For i = 1 To 3
If i= 2 Then Goto JUMP
Msgbox(i)
JUMP:
Next

A long as the if-condition (i = 2) is not met it works but if i=2 then it goes to JUMP but on reaching "Next" provides a runtime error "syntax error".

Can anyone help me how this can be made. I also tried "if i=2 Then Next i" but this leads to an error upon compilation.

Regards miklquick
 

petrbury

Member
Licensed User
Longtime User
As I'm not a "professional" I don't know why it doesn't work. But you can try this way

For i = 1 To 3
If i <> 2 Then Msgbox(i)
Next

Regards Petr
 

giannimaione

Well-Known Member
Licensed User
Longtime User
or
B4X:
For i=1 To 3
  If i<>2 Then
     Msgbox(i)
  End If
Next i
 

Cableguy

Expert
Licensed User
Longtime User
Try it this way...
B4X:
For i = 1 To 3
'do what ever HAS to be done always....
If i= 2 Then
'leving this blank will cause the loop to do nothing
else
'Do what ever is left to be don if the condition was not met
End if
Next
 

miklquick

Member
Licensed User
Thank you all for your help.

it appears that the if-clause is the only solution.

I know that "goto"s are not very good and should normally be avoided but in my case it would have made the code easier and shorter as the "MsgBox(i)" stood for a complex code and a further if-clause makes the code even more complex.

Thanks anyway

Miklquick
 

agraham

Expert
Licensed User
Longtime User
I would have expected that to work as it is jumping within the same scope, and indeed it does work as expected if it is optimised compiled. I think, perhaps wrongly, that it would have worked in the past in the IDE or a legacy app. Maybe Erel has changed something.
 

klaus

Expert
Licensed User
Longtime User
Hi miklquick,

I don't really understand in what the code with the Goto
B4X:
For i = 1 To 3
  If i= 2 Then Goto JUMP
    Msgbox(i)
JUMP:
Next

is easier or shorter than giannimaione one's.
B4X:
For i=1 To 3
  If i<>2 Then
     Msgbox(i)
  End If
Next i

The only difference is the statement i<>2 instead of i=2 and JUMP is replaced by End If.

As the code replacing MsgBox(i) is elatively long you could also use this code to make it better readable:
B4X:
For i=1 to 3
  If i<>2 Then
    DoSomething
  End If
Next
 
 
Sub DoSomething
  MsgBox(i)
  ...
  ...
End Sub

Anyway there are always several solutions.

Best regards
 
Last edited:
Top