For loop question

Blitz3D Forums/Blitz3D Beginners Area/For loop question

RemiD(Posted 2014) [#1]
Hello :)


I have a simple question, not really important, just by curiosity :

Sometimes i have a Count variable in my code :
;Let's say that Count is equal to 10
For Id% = 1 to Count
 ;Debuglog("Id = "+Id)
Next

In this case no problem.


But sometimes it happens that the Count variable is equal to 0 :
;Let's say that Count is equal to 0
For Id% = 1 to Count
 ;Debuglog("Id = "+Id)
Next

In this case Blitz3d will not display an error, but why ?
Is it because the Id% value is already superior to the max value (0) ?


Normally i add a check to prevent an error, like this :
;Let's say that Count is equal to 0
If(Count > 0)
 For Id% = 1 to Count
  ;Debuglog("Id = "+Id)
 Next
Endif

But it seems useless because there is no error even if Count is equal to 0...


Your thoughts about that ?

Thanks,


Kryzon(Posted 2014) [#2]
Every time before the FOR loop iterates it tests the condition "currentIndex <= maximumIndex," and in your case it's "Id <= Count."

If the test fails (the condition is false, so "Id" has a greater value than "Count"), then the loop exits.
In the second code it leaves the loop without running the code inside it at all, as "Id" is already greater than "Count."

A target value of zero or less can be used with the "Step [negative value]" expression.
;Let's say that Count is equal to 0
For Id% = 1 to Count Step -1
 ;Debuglog("Id = "+Id)
Next
In C you have greater control as to what is the condition, increment/decrement etc.
https://en.wikipedia.org/wiki/For_loop#Traditional_for_loops


Stevie G(Posted 2014) [#3]

Is it because the Id% value is already superior to the max value (0) ?



Yes. The opposite is also true, using a negative step. The following will not execute either.

count = 11

For Id% = 10 To Count Step -1
  Print id
Next


IMO, as long as you know what the expected behaviour is then no reason why you can't use it to your advantage.


fox95871(Posted 2014) [#4]
That happens to me sometimes too, I just do trial and error til it works. "Oh, this time only zero to ninety nine will work? One to a hundred worked fine on the other one."


Floyd(Posted 2014) [#5]
;Let's say that Count is equal to 0
For Id% = 1 to Count
;Debuglog("Id = "+Id)
Next

In this case Blitz3d will not display an error, but why ?


Because there is no error. The program is doing exactly what you intended. Count is the number of times the loop should be executed. When count is zero the loop is executed zero times.


RemiD(Posted 2014) [#6]
Ok thanks for the explanations guys.