why cannot assign to function call

Mark Wooding mdw at distorted.org.uk
Sun Jan 11 03:41:17 CET 2009

Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> There are actually three fundamental characteristics of pass-by-reference:
> * passing a value by reference does not lead to the value being copied, 
> in contrast with pass-by-value where it does;
> * modifications to the value passed by reference are visible to the 
> caller;
> * assignments to the value passed by reference are visible to the
>   caller.

I've given an extensive definition of pass-by-reference.  Distilling and
paraphrasing, the main characteristic is that (where possible) new
variables are not created: rather, the parameter names are bound to the
caller's variables.  All three of your above characteristics are
consequences of this one.

But your definition is also flawed: it doesn't distinguish pass-by-
reference from pass-by-value/return (where the caller's variable is
updated from the function parameter's final value when the function
returns).  The difference is detectable if you use global variables,

  variable g = 1

  function foo(x):
    x = 2
    print g

  print g

prints 1 and 1 if you use pass-by-value, 2 and 2 if you use pass-by-
reference, and 1 and 2 if you use pass-by-value/result.

(Within the framework I presented elsewhere, pass-by-value/result is
like pass-by-value, except that we update:

  s'''' = s'''[s'''(e''(n))/l]

where s''' is the store just prior to the return, s'''' is the store
just after the return, n is the parameter name, e'' is the function's
environment, and l is the location designated by the argument
expression, i.e., (l, s') = loc(x, e, s).  If there is no such location,
then the language may either fail to compile the call, or omit the
update operation.)

> Pascal VAR parameters have all three characteristics.

That's because they work as I've suggested.

> Pascal non-VAR parameters have none of them.


> Python parameters have two of the three. C parameters (call-by-value)
> have none of them, except for arrays, where they have all three,
> making arrays in C behave just like Pascal pass-by- reference VAR
> parameters.

Rubbish.  In C:

  void foo(char v[42]) { v = 0; }

Calling this function has no effect on the caller whatsoever.  I've
already explained C arrays, with reference to the ISO standard,
exhaustively: there should be no excuse for continued misunderstanding
of this point.

-- [mdw]

More information about the Python-list mailing list