CIE AS & A Level Computer Science, section 11.3 (Structured programming)
Passing parameters
When a procedure or function is called, the arguments are passed to its parameters in one of two ways.
By value (BYVAL)
A copy of the argument is passed. The procedure can change its copy, but the original is not changed.
By reference (BYREF)
The address of the argument is passed, so the procedure works on the original variable. Any change is made to the caller's variable.
PROCEDURE AddOne(BYVAL A : INTEGER, BYREF B : INTEGER)
A ← A + 1
B ← B + 1
ENDPROCEDURE
X ← 5
Y ← 5
CALL AddOne(X, Y)
OUTPUT X, Y
The output is : X (by value) is unchanged, while Y (by reference) was changed.
| By value | By reference | |
|---|---|---|
| What is passed | a copy | the original (its address) |
| Original changed? | no | yes |
| Use for | inputs | results that must be returned to the caller |
Python
Python passes references to objects. A list is changed by the function, but a number is not:
def add_one(a, b):
a += 1 # a is a new local number
b.append(1) # b is a list, changed in place
x, y = 5, []
add_one(x, y)
print(x, y) # 5 [1]
Terminology
Header, interface, parameter, argument and return value (see the previous pages).
Writing efficient code
- Use loops rather than repeating statements.
- Use procedures and functions to avoid duplicated code.
- Avoid unnecessary calculations inside loops.
- Use meaningful names and comments.
Common mistake: expecting a by-value parameter to change the caller's variable. It only changes the copy. Also, a by-reference parameter should only be used when the procedure really needs to change the original.
Exam tip: say which parameters are by value and which by reference in the header. In a trace question, track the caller's variables separately from the procedure's parameters.
Check yourself
What happens to the original variable when it is passed by value?
It is not changed, because the procedure works on a copy.
When would you pass a parameter by reference?
When the procedure must change the caller’s variable or return a result through it.
What does the procedure header contain?
The name of the procedure and its parameters.