Procedures and BYREF
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
CALL runs a procedure
- A procedure is a named block. It does a job and returns no value.
- Define it with
PROCEDURE…ENDPROCEDURE, and run it withCALL. - Parentheses are written even when there are no parameters.
PROCEDURE Greet()
OUTPUT "Hi"
ENDPROCEDURE
CALL Greet()
By value is the default
- A parameter with no mode is passed by value: the procedure gets a copy.
- Changing the copy does not change the caller's variable.
- You may also write
BYVALin front of the name. It means the same thing.
PROCEDURE Show(N : INTEGER)
N ← N + 1
OUTPUT N
ENDPROCEDURE
DECLARE A : INTEGER
A ← 5
CALL Show(A)
OUTPUT A
BYREF passes the real variable
BYREFmeans the parameter is the caller's variable. A change is still there afterCALL.- If several parameters in a row use the same mode, the guide lets you write the keyword once.
- Do not pass a parameter to a function by reference. Use
BYREFon a procedure.
PROCEDURE Swap(BYREF X : INTEGER, BYREF 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 & "," & B
Common mistakes
CALLbefore a procedure. NeverCALLa function.- IGCSE 0478 has no
BYREF. On that paper every parameter is a copy.
Now you try
- Write a procedure that swaps two integers.
Write a procedure Greet with no parameters that outputs Hi, then CALL it.
Click Run to see the output here.
Write Swap so that BYREF exchanges A and B. Start from A ← 1 and B ← 2, and output 2,1.
Click Run to see the output here.