For loop question
Blitz3D Forums/Blitz3D Beginners Area/For loop question
| ||
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, |
| ||
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) NextIn C you have greater control as to what is the condition, increment/decrement etc. https://en.wikipedia.org/wiki/For_loop#Traditional_for_loops |
| ||
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. |
| ||
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." |
| ||
;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. |
| ||
Ok thanks for the explanations guys. |