Cambridge pseudocode

What BYREF Does in Pseudocode

A parameter is a name the procedure uses for a value the caller handed over. BYVAL means the procedure gets its own copy. BYREF means the procedure is handed the caller’s variable, so an assignment inside the procedure is an assignment out in the caller.

How it works

The swap that does nothing

Leave the keyword off and both parameters are copies. SWAP exchanges X and Y, then throws those copies away. A and B are still 1 and 2.

PROCEDURE SWAP(X : INTEGER, Y : INTEGER)
    DECLARE Temp : INTEGER
    Temp <- X
    X <- Y
    Y <- Temp
ENDPROCEDURE

DECLARE A : INTEGER
DECLARE B : INTEGER
A <- 1
B <- 2
CALL SWAP(A, B)
OUTPUT A
OUTPUT B
Output
1
2

Write BYREF once. It is sticky: it covers Y as well, until a later parameter says BYVAL. Now X and Y are A and B. The procedure writes through them, so the caller sees 2 and 1.

PROCEDURE SWAP(BYREF X : INTEGER, Y : INTEGER)
    DECLARE Temp : INTEGER
    Temp <- X
    X <- Y
    Y <- Temp
ENDPROCEDURE

DECLARE A : INTEGER
DECLARE B : INTEGER
A <- 1
B <- 2
CALL SWAP(A, B)
OUTPUT A
OUTPUT B
Output
2
1

IGCSE procedures are always copies. BYREF and BYVAL are AS & A Level (9618). Both words are soft keywords, so a variable is allowed to be named BYREF.

In Python

Integers do not have BYREF

Assigning to a Python parameter rebinds that local name. The caller’s integer is a different object, so the swap inside the function never touches a and b. You return the new pair, or you swap where a and b actually live.

Python
def swap(x, y):
    x, y = y, x

a, b = 1, 2
swap(a, b)
print(a, b)  # 1 2

a, b = b, a
print(a, b)  # 2 1

A list is shared. The function and the caller hold the same list, so writing into it is the BYREF feeling. That is still not a reference parameter: the name nums was not passed by reference, the list object was shared.

Python
def stamp(box):
    box[0] = 9

nums = [1]
stamp(nums)
print(nums[0])  # 9

Beyond the exam

Two different ideas get called “by reference”

Cambridge BYREF means “this parameter is that variable.” Python, and Java, pass the value of a reference: the function receives a copy of a pointer that still aims at the same object. Rebinding the parameter changes the copy of the pointer. Mutating the object changes what everyone can see. C++ has an actual reference parameter, which is the Cambridge meaning. Converting a scalar BYREF to Python keeps the function, and warns that assignments inside it will not come back to the caller.

Run the example in the pseudocode compiler online, or read the matching section of the Cambridge pseudocode guide.