Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 61 ยท Code Generation and Runtimes

Parameter Passing Modes and Activation Records

Compare call by value, reference, copy-restore and name, see how arguments live in activation records, and compare access links with a display, using runnable models.

When you write f(x, y), a compiler has to decide what the function receives. Is it a copy of the values, so that changes inside f are invisible outside? Is it the variables themselves, so that f can change them? Or is it the expressions, to be evaluated whenever f uses them? Different languages made different choices, and the choice changes what programs mean, not just how fast they run.

The runtime environments lesson showed the activation record that a call creates. This lesson focuses on the arguments in that record: the four classic parameter-passing modes, what each one stores in the frame, the surprising results you get when you mix them with aliasing, and the two ways to reach the variables of enclosing procedures, access links and a display.

Vocabulary: formal and actual parameters

The names in the function definition are the formal parameters. The expressions at the call site are the actual parameters (arguments). A parameter-passing mode defines the link between the two. The terms l-value (an expression that denotes a storage location, like i or a[i]) and r-value (just a value, like 3 + 4) matter here: some modes need an l-value, others work with any expression.

The four modes

Call by value. The caller evaluates each actual parameter and copies the value into the callee's frame. The formal parameter is an ordinary local variable. Changes inside the callee are lost when it returns. This is the default of C, Java (including for object references), JavaScript and Python (which pass references to objects, a variant described later). It is simple and safe, but copying large structures is slow.

Call by reference. The caller passes the address of the actual parameter, and the formal parameter is an alias for that variable: every read and write inside the callee goes through the pointer. The callee can modify the caller's variable, and big objects are passed without copying. C++ references (int&), Pascal var parameters and Fortran work this way. If the actual parameter is not an l-value (such as 3 + 4), the compiler creates a temporary and passes its address.

Call by copy-restore (also called value-result or copy-in copy-out). The value is copied in at the call, as with call by value. When the callee returns, the final value of the formal parameter is copied back into the actual parameter, whose address was computed at the time of the call. It looks like call by reference as long as nothing else touches the variable during the call, but behaves differently with aliasing. Ada's in out parameters may use it, and some Fortran compilers did.

Call by name. The actual parameter is substituted textually (conceptually) for every occurrence of the formal parameter, and is evaluated again each time the callee uses it, in the environment of the caller. The implementation passes a small piece of code called a thunk that computes the value (or the address) on demand. Algol 60 introduced it, and its descendants live on in lazy evaluation and in macro systems. It is powerful and confusing.

flowchart LR
    V["By value: callee gets a copy of the value"] --> M1["Frame holds the value"]
    R["By reference: callee gets the address"] --> M2["Frame holds a pointer"]
    C["By copy-restore: copy in, copy out at return"] --> M3["Frame holds a copy, plus the target address"]
    N["By name: callee gets code to compute it"] --> M4["Frame holds a thunk"]

What the argument slot of the activation record contains, depending on the mode.

Running the four modes side by side

The program below implements all four modes with small objects: a Cell for a local copy, a Ref that remembers an address, and a Thunk that stores expression text and evaluates it at every use. Then it calls the same procedures in every mode so that you can compare the outcomes.

Python Four parameter-passing modes, one program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three experiments teach different lessons:

  1. swap(i, a[i]) with i = 1. Call by value changes nothing, as expected. Call by reference and copy-restore both end with i = 10 and a[1] = 1: the swap worked on the locations that i and a[1] had at the time of the call. Call by name breaks: x = y assigns i = a[i], which changes i to 10, and then y = t writes to a[i], now a[10], which is a different element. The array ends up with a stray 10: 1. A function as simple as swap cannot be written reliably with call by name. This is the famous example against it.
  2. f(g, g) with the same variable twice. With call by reference the two formals are aliases for one variable, so after x is incremented, y reads 6. With copy-restore, y is a separate copy and still reads 5, and when the function returns the copies are written back in order, so the final value of g depends on the order of copy-out (here the last one wins and gives 5). With call by name y re-evaluates g and sees 6. Aliasing is what separates reference from copy-restore.
  3. Jensen's device (sigma(i, 1, 4, i * i)). With call by name, the loop variable and the term are passed as thunks: the procedure assigns to i and each time it asks for term, the expression i * i is evaluated with the current i. One generic summation procedure computes both sums of squares and sums of array elements. This is the legitimate and clever use of call by name, but it is the same mechanism that broke swap.

Other mechanisms in real languages

  • Call by sharing (Python, Java objects, JavaScript): the value that is copied is a reference to an object. The callee can change the object (visible to the caller), but assigning a new object to its own parameter does not affect the caller. This is call by value, where the value happens to be a pointer.
  • Call by need (Haskell): call by name with caching. The thunk is evaluated at most once and its result is remembered, giving laziness without the repeated evaluation.
  • Const reference (C++ const T&): reference-passing for speed, with the compiler forbidding writes, so it behaves like call by value for the programmer.
  • Move semantics (C++ T&&, Rust): the callee takes ownership of the value without copying.

Arguments in the activation record

How do these modes look in a compiled program? Take p(a, b) where a is passed by value and b by reference. The caller:

  1. Evaluates a and stores the value in the argument area of the new frame (or in a register, depending on the calling convention).
  2. Computes the address of b and stores that in the next slot.
  3. Pushes the return address and jumps.

Inside p, reading a is a load from its slot. Reading b is a load of the pointer followed by a second load through it. Writing to b stores through the pointer. A thunk (call by name) is a pair (code address, environment pointer): reading the parameter means calling the code, which makes this the slowest mode.

Large aggregates are rarely copied into the frame. Compilers pass arrays by passing the address (as C does, which makes arrays look as if they were passed by reference), and a struct passed by value is usually copied into the frame or, for big structs, into a caller-allocated temporary whose address is passed.

Reaching variables of enclosing procedures

In a language with nested procedures, a procedure may use variables of the procedures that contain it. Two implementation techniques exist (the first one is introduced in runtime environments):

  • Access links (static links). Each frame stores a pointer to the frame of its lexically enclosing procedure. To reach a variable that is d levels up, follow d links. The cost grows with the nesting distance, but entering and leaving a procedure is cheap.
  • Display. A global array display[1..n] where display[k] points to the newest active frame at nesting level k. A variable at level k is reached in one step through display[k]. The price is on entry: a procedure at level L saves the old display[L] in its own frame, installs itself, and restores the old value when it returns.

The simulation shows the display for a call chain that nests three levels and where q calls p recursively.

Python A display during nested and recursive calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When the second p is entered, display[2] switches to the new frame, and the first one's pointer is stored in the new frame's saved slot. After two returns, the display is restored to point to the first p and the first q. A deeply nested program with a hot inner loop that uses outer variables gains from the display, while a program with shallow nesting and many calls is better served by access links. Most modern languages avoid the problem by not allowing nested functions to capture variables except through closures, which store captured values explicitly.

Choosing a mode in language design

Mode Callee can change caller's variable Cost Aliasing surprises Used by
Value No Copy of the value None C, Java, Python (sharing), Go
Reference Yes One pointer, extra loads Yes C++ &, Pascal var, Fortran
Copy-restore Yes, at return Copy in and copy out Order-dependent Ada in out (allowed), old Fortran
Name Yes, if l-value Thunk call per use Many Algol 60, macros
Need No Thunk, evaluated once None (pure languages) Haskell

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function increments its parameter. After the call, the caller's variable is unchanged. Which mode is the likely cause?

    With call by value the callee works on a copy of the argument, so changes disappear when the frame is popped.
  2. 2. What is the difference between call by reference and copy-restore when the same variable is passed twice?

    Aliasing makes writes through one reference visible through the other, but copies do not see each other's changes until copy-out.
  3. 3. Why does swap(i, a[i]) fail under call by name?

    After x = y assigns to i, the expression a[i] denotes a new element, so the final write goes to the wrong place.
  4. 4. What does a display give you compared with access links?

    The display holds a pointer to the newest frame of each nesting level, so one lookup reaches it. Procedure entry and exit have to maintain the array.
  5. 5. What does the argument slot hold for a call-by-name parameter?

    Because the expression must be re-evaluated in the caller's environment on every use, the callee receives a small closure.

Summary

  • Formal parameters are the names in a definition, actual parameters are the arguments at the call. The passing mode defines how they connect.
  • Call by value copies the value, by reference passes an address (aliasing), copy-restore copies in and out at return, and by name passes a thunk evaluated at every use.
  • Call by name makes swap(i, a[i]) fail and enables Jensen's device. Reference and copy-restore differ only when the same location is reachable twice.
  • Languages such as Python and Java use call by sharing: values are copied, but the values are references. Haskell uses call by need.
  • In an activation record, the argument slot holds a value, an address, a copy plus a return address, or a thunk.
  • Access links walk up the nesting levels. A display jumps straight to any level, at the cost of saving and restoring entries on every call.

Next, see how target code is produced in Code Generation Basics.