Re: Variable Scope
Rich Klender wrote:
>
> Let's say I have the following:
>
> function somefunc(integer C)
> integer a,b,c
>
> a=1
> b=2
> c=3
> return c
> end function
>
> Ok, now in my main program, because c was returned, I'll be able to "see"
> that c=3.
Wrong. You'll have the /value/ 3, wherever you put it, but on return from the
function the /variable/ c *NO LONGER EXISTS*. You might, for instance code:
z=somefunc(x)
Then z would have the value 3 from c, and ?z would display 3, but if you wrote
?c then it would complain that c has not been defined.
Effectively, to deal with recursion, when you call a routine it creates space to
hold the locals and on return it frees that space. (See PS)
> However, if I do this:
>
> function somefunc(integer C)
> global integer a,b,c
>
> a=1
> b=2
> c=3
> return c
> end function
What I think you mean is:
integer a,b,c
procedure someproc()
a=1
b=2
c=3
end procedure
Because a,b,c are defined outside the routine, they persist when it exits.
The real point of scope is:
integer a,b
procedure p()
integer b
a=1
b=2
end procedure
Now because there is no "a" defined within p(), the first line updates the
variable outside, but in the second line the local "b" is said to take precedence
and on exit you will find the outer "b" was not modified.
You never actually want to give two variables the same name, but when you start
writing thousands of lines of code, it becomes almost inevitable.
The best example I can give you is "for i=", which you will see many times
in any reasonably-sized program. Hundreds of different "i" may thus exist, but
thanks to scope it uses the one you meant.
Regards,
Pete
PS Technically, the actual implementation always has a space somewhere for
locals to speed things up a bit on the first call, but all programs would run the
same if that space were created at the point of the call and trashed on return,
they would just be a fraction slower.
|
Not Categorized, Please Help
|
|