Can global variable be passed into Python function?
steve+comp.lang.python at pearwood.info
Sat Feb 22 08:18:27 CET 2014
On Sat, 22 Feb 2014 17:36:52 +1100, Chris Angelico wrote:
> On Sat, Feb 22, 2014 at 6:20 AM, Marko Rauhamaa <marko at pacujo.net>
>> On the question of how variables can be passed to functions, C, of
>> course, has the & operator and Pascal has the "var" keyword.
> That doesn't pass a variable into a function, though. It passes the
> address of that variable, and C lets you stuff something into an
> address. That's not the same thing.
Be careful about conflating the implementation with the interface. As I
understand it, the interface C literally is that &x gives you the address
of x. But that's not what the var keyword is for in Pascal (although that
may be how it is implemented).
In Pascal, if you have a function or procedure:
procedure plus(a:integer, var b:integer);
b := a+b;
and a couple of variables in some other scope, for simplicity lets make
foo := 23;
bar := 1;
the output will be 24. If we could peek into procedure plus, we would see
that argument a was a *copy* of global bar, while argument b wasn't
merely a copy of foo, it actually was foo. So assigning to b inside plus
is the same as assigning to foo in the global scope.
If we added a call:
to the main program, then inside plus argument a would have the value 2,
and argument b would now be precisely the same variable as global bar.
After the procedure returns, bar would have the value 3.
Now I daresay that under the hood, Pascal is passing the address of foo
(or bar) to the procedure plus, but inside plus you don't see that
address as the value of b. You see the value of foo (or bar).
C does not do that -- you have to manually manage the pointers yourself,
while Pascal does it for you. And Python also has nothing like that.
More information about the Python-list