why cannot assign to function call

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jan 11 09:27:12 EST 2009


On Sun, 11 Jan 2009 03:25:24 +0000, Mark Wooding wrote:

> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> 
>> I don't believe it is a red-herring. As I understand it, Mark and Joe
>> insist that C is pass-by-value *even in the case of arrays*, despite
>> the semantics of array passing being identical to the semantics of
>> pass-by- reference in (say) Pascal.
> 
> But they aren't.  I've provided several examples to show this.

Here's some p-b-r code in Pascal:


program main(input, output);
  type
    arraytype = array[1..2] of integer;
  var
    arr: arraytype;

procedure foo(var bar: arraytype);
  begin
    bar[2] := 42;
    writeln(' bar = ', bar[1], ' ', bar[2]);
  end;

begin
  arr[1] := 0;
  arr[2] := 0;
  writeln(' Before: arr = ', arr[1], ' ', arr[2]);
  foo(arr);
  writeln(' After: arr = ', arr[1], ' ', arr[2]);
end.


Here's the output from running that code:


 Before: arr = 0 0
 bar = 0 42
 After: arr = 0 42



Here's the equivalent C code, as close to an exact one-to-one 
correspondence as I can come up with:


#include<stdio.h>

void foo(int bar[2])
{
  bar[1] = 42;
  printf("\n bar = %d %d ", bar[0], bar[1]);
}

int main()
{
        int arr[2]={0,0};
        printf("\n Before: arr = %d %d ", arr[0], arr[1]);
        foo(arr);
        printf("\n After: arr = %d %d ", arr[0], arr[1]);
        printf("\n");
        return 0;
}


And the output of it:

 Before: arr = 0 0
 bar = 0 42
 After: arr = 0 42


If it walks like pass-by-reference, and smells like pass-by-reference, 
and swims like pass-by-reference, is it still your contention that it is 
pass-by-value?



> For the purpose of clearing this up once and for all: arrays, in C, are
> `don't-pass-at-all'.  There is no way -- none whatever -- of declaring a
> function parameter as having array type.

It looks just like I did precisely that here:

void foo(int bar[2])

I guess this is where you explain again that arrays in C are "bizarre", 
and that while "int arr[2]" inside a function body means "declare an 
array of two ints and call it 'arr'", the exact same declaration in a 
function parameter list means something else. Possibly:

"Declare a pointer which points to an array of two ints, call the pointer 
'arr', and dereference the pointer every time it is used inside the 
function as if you were referring to the array directly".

Am I close?



-- 
Steven



More information about the Python-list mailing list