Recursion question

Blitz3D Forums/Blitz3D Programming/Recursion question

jfk EO-11110(Posted 2007) [#1]
I'm not sure about the following:

when I use a recurive function call, eg:

global b
test()
waitkey()
end

function test()
local a=rand(100)
print a
b=b+1
if b<2 then test()
b=b-1
print a
waitkey()
end function

(b is the recursion depth limiter here)

THe question is: when I got a local variable in a function that is called recursively, will always the same A be used (since it's in the same function), or has each "instance" of the recursion its own A variable, that is only affected by the immediate instance?

Right now it seems to me the second is true. but I'd like to see this confirmed.


GfK(Posted 2007) [#2]
Each instance has its own A var.

[edit]

...as is demonstrated here:
Global count
Recursion()
Function recursion()
	count = count + 1
	Print "Recursion function called " + count + " times."
	A = A + 1
	Print "A = " + A
	If count = 100 Then End
	Recursion()
End Function



jfk EO-11110(Posted 2007) [#3]
Thanks.


H&K(Posted 2007) [#4]
@GFK small change to youre code to show something else
Recursion()
Function recursion()
	Global count=0   'Only Acted apon once
        Local a=0	 'Acted apon every recursion/function call

        count = count + 1
	Print "Recursion function called " + count + " times."
	A = A + 1
	Print "A = " + A
	If count = 100 Then End
	Recursion()
End Function

Global in a function is static, and is only initialized once. Locals in a function arent static, and are initalized each call to the function

(Only do this when you are really really sure you dont want to access the count (in this case) anywhere else, and in this case is stupid to be used, cos once its set to 100, it stays at 100 and never drops cos we are just "ending", but in a real situation, before the returns would need to count:-1)


WendellM(Posted 2007) [#5]
Global in a function is static

In BlitzMax, yes. In Blitz3D (which this thread is presumably about), static vars aren't possible inside a function, so they have to go outside as a Global. That was one thing I was so glad to see added to BlitzMax: functions with static vars could be self-contained and didn't need Globals scattered outside.


H&K(Posted 2007) [#6]
Woops

Errr, Well done Wendel for spoting my deliberate mistake ;)

Note to self: Read which Board a Qustion is in
(I had wondered why GFK hadnt used Local or strict)