Sub topic 4
Parameter Passing: Value, Reference, Copy-Restore, and Name
Assume you know functions, variables, assignment, and basic set or state reasoning. This chapter uses the idea that an argument is an actual parameter and the receiving function variable is a formal parameter.
Four parameter-passing modes
A parameter-passing mode defines how the actual argument and formal parameter are connected.
| Mode | What enters the function | Effect of assignment to the formal |
|---|---|---|
| Call by value | A copied value | Changes only the formal |
| Call by reference | An alias to the actual variable | Changes the actual immediately |
| Copy-restore | A value copied in and copied out later | Changes the actual on return |
| Call by name | A delayed computation for the argument | Re-evaluates the argument when used |
Call by value
The function receives an independent copy. This prevents the function from changing the caller's variable directly.
#include <stdio.h>
void add_one(int x) {
x = x + 1;
}
int main(void) {
int a = 4;
add_one(a);
printf("%d\n", a); // 4
return 0;
}The formal parameter x is stored separately from a. C uses call by value, although a pointer value can be passed to simulate reference behavior.
Call by reference
The formal parameter denotes the same storage as the actual parameter. An assignment through the formal changes the caller's variable.
For example, a reference-style swap(x, y) can exchange two variables directly. This mode is efficient because it avoids copying large objects, but aliasing can make reasoning difficult. Aliasing occurs when two names access the same storage.
Copy-restore
Copy-restore is also called value-result. The function receives a private copy, then writes the final copy back to the actual argument when the function returns.
procedure set_both(x, y):
x := 1
y := 2
a := 0
set_both(a, a)Here, both formals initially receive 0. On return, two results must be copied into the same variable. If x is restored first, then a becomes 1 and finally 2. If y is restored first, the final value becomes 1. Therefore, overlapping actual arguments make the result language-dependent or undefined unless the language specifies an order.
Call by name
Call by name passes an unevaluated argument, conceptually like a thunk, which is a parameterless procedure that computes the argument when needed.
procedure twice(x):
return x + x
i := 1
twice(i := i + 1)With call by name, each use of x can re-evaluate i := i + 1. The two uses may therefore observe different values. This resembles textual substitution, but the substituted expression is evaluated in the caller's environment.
Exercise
Under call by value, what is the value of a after add_one(a) when a starts at 4?
Show answer
a remains 4 because the function modifies only its local copy.