PDA

View Full Version : If (...) then Next problem



ChandraMDE
06-05-2013, 09:54
Hello, Eros.
I have 2 simple codes and they are:


'**********CODE - 1
Uses "console"

Dim i, j As Integer

For i = 1 To 10
For j = 1 To 3
If i=5 Then Next
Console_Write(i&" ")
Next j
PrintL
Next i
WaitKey()

-----------------------------------------------------------
This is the CODE-1 result:
1 1 1
2 2 2
3 3 3
4 4 4
5 6 6 6
7 7 7
8 8 8
9 9 9
10 10 10
-----------------------------------------------------------


'**********CODE - 2
Uses "console"

Dim i, j As Integer

For i = 1 To 10
For j = 1 To 3
If i=5 Then
Next
End If
Console_Write(i&" ")
Next j
PrintL
Next i
WaitKey()

The 1st code interpreted succesfully, while the 2nd was generating error 32.
Please advice.

Thanks and Regards.

Petr Schreiber
06-05-2013, 10:07
Thanks for asking this question. Your approach has its logic, but it is done differentely in ThinBASIC.

The thing is - FOR/NEXT is a fixed code block, the number of FOR and NEXT must match. There cannot be FOR wihout NEXT or NEXT without FOR. It would be like Tom without Jerry or Jerry without Tom :)

In case you need to iterate before reaching NEXT, you need to use ITERATE FOR keyword.

One littl detail - you don't need to specify variable after NEXT, it is optional. ThinBASIC is able to keep track of the nesting level, so you don't have to worry about it.

See corrected codes below.

Code 1:


'**********CODE - 1
Uses "console"

Dim i, j As Integer

For i = 1 To 10
For j = 1 To 3

If i = 5 Then Iterate For

Print (i + " ")
Next
PrintL
Next

WaitKey()


Code 2:


'**********CODE - 2
Uses "console"

Dim i, j As Integer

For i = 1 To 10
For j = 1 To 3

If i=5 Then
Iterate For
End If

Print (i + " ")
Next
PrintL
Next

WaitKey()


Petr

P.S. You can see the first code works strange too - it writes one 5, although it should not. I think it is a bug and I made a report here (http://www.thinbasic.com/community/project.php?issueid=397). The ITERATE FOR approach will work always.

ChandraMDE
06-05-2013, 10:31
Petr, thank you for a the answer.
I like about the Tom without Jerry or Jerry without Tom phrase.
So, Iterate For is what I'm looking for.

Thanks and Best Regards. :)