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

 
Author Message
pjc30943



Joined: 02 Dec 2005

Posted: 20 August 2008, 0:27 AM    Post subject: For...Loop does not work for negative indexes?

This code

Code:
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:
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:
   const minIndex as integer = -3, maxIndex as integer = -1


correctly executes as

Code:
ZBasic v2.5.5
Begin Loop
Inside Loop
Inside Loop
Inside Loop
Done with Loop


Any ideas about what's going on?
Back to top
dkinzer
Site Admin


Joined: 03 Sep 2005
Location: Portland, OR

Posted: 20 August 2008, 2:19 AM    Post subject: Re: For...Loop does not work for negative indexes?

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:
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
Back to top
Display posts from previous:   
Page 1 of 1

 



ZBasic Microcontrollers Home
All content Copyright © 2005, 2006, 2007, 2008 Elba Corp. All Rights Reserved.
Opinions expressed in posts are those of the author and not necessarily those of Elba Corp.
Powered by phpBB © 2001, 2005 phpBB Group