Pointers and Function Arguments

Shang passes arguments to functions by value, so the called function cannot directly alter the value of an argument in the calling function since what it receives is only a copy of the variable of the caller. For example, if one wishes to write a function to interchange the values of two variables, the following will not work
A = "AAA";
B = "BBB";
swap = function (a, b) -> ()
              temp = a;
              a = b;
              b = temp;
        end
swap(A, B);
A
B
since what swap receives are the copies of A and B.

However, if pointers to local variables are passed then it's possible to modify the values of the local variables of the calling function. For example, the swap function can be implemented the following way

A = "AAA";
B = "BBB";
swap = function (a, b) -> ()
              temp = a>>;  // temp gets the value a pointing to
              a>>= b>>;   /*  the location a pointing to gets
                              the value b pointing to
                           */
              b>>= temp;  /* the location b pointing to gets
                             the value of temp
                           */
        end
swap(>>A, >>B);            // pass pointers to A and B to swap
A
B
When swap(»A, »B) is being executed, a copy of »A and a copy of »B are passed to swap. However, those two copies still point to A and B respectively, which are values of the local variables of the caller. Therefore, in function swap, when updating the values these pointers pointing to, the values of the local variables of the caller are altered.



oz 2009-12-22