For To and for Until

BlitzMax Forums/BlitzMax Beginners Area/For To and for Until

ziggy(Posted 2007) [#1]
Is there any diference between For x = 1 to 10 and For X = 1 until 10 ?


Azathoth(Posted 2007) [#2]
Until stops before reaching the number, so it would be like For X=1 to 9.


Gabriel(Posted 2007) [#3]
Yes. Until 10 will not run the loop when X=10. To 10 will run the loop when X=10 and then it will exit. So it will loop one more time with To over Until.


ImaginaryHuman(Posted 2007) [#4]
The Until is like a While loop, checking the value at the top of the loop and then deciding whether to proceed, whereas the regular For loop runs at least once and checks at the end.


TaskMaster(Posted 2007) [#5]
No, the For/To loop does not run "at least once".

For x=2 to 1

will not run once.

For x=1 to 1

will run once.

For x=1 Until 1

will not run once.


ziggy(Posted 2007) [#6]
Thanks! It is not in the documentation and I thought they did the same.


CS_TBL(Posted 2007) [#7]
It's a bit confusing that help/f1 on 'Until' goes to the Until in a loop like repeat. The For-help doesn't mention Until. Ohwell, I covered these loops in the proposed new help from assari..


TomToad(Posted 2007) [#8]
It's under Help/Language/Program Flow


JazzieB(Posted 2007) [#9]
Using For..Until is actually quite useful and I find myself using it all the time. For example, if you have the width of an image in a variable and you want to step through it a pixel at a time, you don't have to have...

For x:int=0 To (imageWidth-1)

You can just have

For x:int=0 Until imageWidth

Just saves having to stick -1 on the end of everything.


TaskMaster(Posted 2007) [#10]
I personally don't use Until. But that is just a personal choice. For me, it is just easier to only use one of them (For-To) so they are all the same. Then I don't have to think about whether there is suppose to be a -1 because it is a To or if it is an Until and I don't need it.


Czar Flavius(Posted 2007) [#11]
Is using until faster because it doesn't need to process the -1?


Azathoth(Posted 2007) [#12]
I don't think so because it only gets called once anyway for the whole loop.

For i=0 To F()
Next

Function F()
	Print "Called"
	Return 10
EndFunction



Otus(Posted 2007) [#13]
When I tested them for speed, it seemed to be slower with Until than To num-1. No idea why.


ziggy(Posted 2007) [#14]
I did several test with very bin iterations and I did not see any performance diferences.


ImaginaryHuman(Posted 2007) [#15]
I wouldn't think there'd be hardly any speed difference if any. Internally it's probably doing a simple `compare` to see if the highest value allowed is > the current value, and the only difference for the Until version is it checks if it is =, or something along those lines.