Pass-by-Reference Arguments

Sometimes it is desirable for a function to intentionally modify its arguments, perhaps to return multiple value lists. In such cases the argument can be passed by reference with the $& variable syntax:

<A NAME=square x>
  <$x = ($x * $x)>
</A>

<A NAME=main>
  <$y = 5>
  <square x=$&y>
  y squared is: $y
</A>

Here the $y argument is passed to $x by reference. A reference argument is not copied to its parameter; instead the parameter becomes an "alias" for the caller's argument. Any modifications to the parameter in the function will change the caller's argument too: the two are the same variable. Thus, when $x is modified in the square function above, $y in main is changed as well, since it was passed by reference when square was called.

Note that unlike other languages, a pass-by-reference argument is determined by the caller, not the function. I.e. the function declaration has nothing to do with whether an argument is a reference or not; it depends on how it is called. Thus, unlike C++ references, the caller can always control whether its arguments are modifiable or not, even if the declaration of the function itself is unknown or changes.


Copyright © Thunderstone Software     Last updated: Oct 24 2023
Copyright © 2024 Thunderstone Software LLC. All rights reserved.