For-Next. Why variable grows?

Everything else that doesn't fall into one of the other PB categories.
User avatar
einander
Enthusiast
Enthusiast
Posts: 744
Joined: Thu Jun 26, 2003 2:09 am
Location: Spain (Galicia)

Post by einander »

From the PB Help:
For <variable> = <expression1> To <expression2> [Step <constant>]
It seems possible to use <variable> instead of <constant> as false Step value, changing the For and To values INSIDE the loop.

Code: Select all

q=10
For i= 0 To q
i+1
q+1
Debug Str(i)+" "+Str(q)
Next
Dunno if this s is legal, but it compiles OK in PB 3.92 and 3.93
User avatar
Psychophanta
Always Here
Always Here
Posts: 5153
Joined: Wed Jun 11, 2003 9:33 pm
Location: Anare
Contact:

Post by Psychophanta »

Einander, have you tried result with gw-basic?
Froggerprogger wrote: A For-loop (with positive STEP) is processed in this way:
- check the value of the countervariable against the TO-variable's value
- if both are same, or countervariable < TO-variable then increase the countervariable by step

So if countervariable and TO-variable point to the same variable, e.g. 'i' then both are increased, and will always have the same result => endless loop
Exact. The point is that PB checks if variable < or = than TO-variable, if equal, then increment it.
It just do same that this in C:

Code: Select all

for (var=var;var<=var;var++) {}
1. Assign var = var
2. Check condition var<=var.
3. If true (just it is), then do the {} tasks, else go step 6.
4. Do var++
5. Go to step 2.
6. } End. Out of loop

This is how PB do a For-Next. Am i lying?
http://www.zeitgeistmovie.com

while (world==business) world+=mafia;
Froggerprogger
Enthusiast
Enthusiast
Posts: 423
Joined: Fri Apr 25, 2003 5:22 pm
Contact:

Post by Froggerprogger »

Yes @Psychophanta

Code: Select all

For i=0 To a Step 3
Next
is >exactly< the same as

Code: Select all

i=0
While i <= a
...
i+3
Wend
For negative step just replace '<=' by '>='
So you can easily assign a new value to i or a inside the body and affect the loop's behaviour in a strange way.
%1>>1+1*1/1-1!1|1&1<<$1=1
User avatar
einander
Enthusiast
Enthusiast
Posts: 744
Joined: Thu Jun 26, 2003 2:09 am
Location: Spain (Galicia)

Post by einander »

@Psychophanta:
I don't have gw-basic, but in GFAbasic it's also possible to change the TO value inside the loop.

Try this to see the To value changing:

Code: Select all

OpenWindow(0,0,0,400,400,#PB_Window_BorderLess ,"")   
StartDrawing(WindowOutput())
r.f=30
q=1130

For i=10 To q 
i+2
q-r
r-0.5
Circle(i,q,4)
Debug q
Next
StopDrawing()

Repeat
Until WaitWindowEvent() = #PB_Event_CloseWindow 
Post Reply