For...Loop does not work for negative indexes?

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
pjc30943
Posts: 220
Joined: 01 December 2005, 18:45 PM

For...Loop does not work for negative indexes?

Post by pjc30943 »

This code

Code: Select all

Option TargetCPU zx1280n

Sub Main()
	dim Index as integer
	const minIndex as integer = -1, maxIndex as integer = 1
	
	debug.print "Begin Loop"
	for Index = minIndex to maxIndex
		debug.print "Inside Loop"
	next
	debug.print "Done with Loop"
End Sub
prints out

Code: Select all

ZBasic v2.5.5
Begin Loop
Done with Loop

Based on the documentation, it seems that a negative minIndex should work, although in this case the loop never executes.
It would seem that negative integers are not supported, but

Code: Select all

	const minIndex as integer = -3, maxIndex as integer = -1
correctly executes as

Code: Select all

ZBasic v2.5.5
Begin Loop
Inside Loop
Inside Loop
Inside Loop
Done with Loop
Any ideas about what's going on?
Paul
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: For...Loop does not work for negative indexes?

Post by dkinzer »

pjc30943 wrote:Based on the documentation, it seems that a negative minIndex should work, although in this case the loop never executes.
Quite so. You've discovered a previously undetected front end optimization error related to the interpretation of numeric constant values. The source of the problem has been found and corrected. This change will be in the next round of regression testing and we'll create a test case to cover it.

Thank you for providing a concise test case. That makes resolving problems easier than it might otherwise be.

In the mean time, you can turn off optimization and the problem will disappear. This shouldn't have any significant effect on your program since it is native mode and the back end compiler does its own optimization which is unaffected by --optimize=no-optimize. The second workaround is to introduce intermediate variables as illustrated below. Again, this shouldn't have any significant effect on your program because the back end compiler will optimize them away.

Code: Select all

Sub Main()
   Dim Index as Integer
   Const minIndex as Integer = -1, maxIndex as Integer = 1
   Dim startIdx as Integer = minIndex
   Dim endIdx as Integer = maxIndex

   Debug.Print "Begin Loop"
   For Index = startIdx to endIdx
      Debug.Print "Inside Loop"
   Next
   Debug.Print "Done with Loop"
End Sub
- Don Kinzer
Post Reply