For To and for Until
BlitzMax Forums/BlitzMax Beginners Area/For To and for Until
| ||
Is there any diference between For x = 1 to 10 and For X = 1 until 10 ? |
| ||
Until stops before reaching the number, so it would be like For X=1 to 9. |
| ||
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. |
| ||
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. |
| ||
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. |
| ||
Thanks! It is not in the documentation and I thought they did the same. |
| ||
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.. |
| ||
It's under Help/Language/Program Flow |
| ||
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. |
| ||
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. |
| ||
Is using until faster because it doesn't need to process the -1? |
| ||
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 |
| ||
When I tested them for speed, it seemed to be slower with Until than To num-1. No idea why. |
| ||
I did several test with very bin iterations and I did not see any performance diferences. |
| ||
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. |