Procedures and BYREF
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
- If no mode has been specified, parameters start by value: the procedure gets a copy.
- Changing the copy does not change the caller's variable.
BYVALexplicitly selects a copy. At the start of a parameter list it is the default; afterBYREF, writeBYVALto switch back.
PROCEDURE Show(Number : INTEGER)
Number ← Number + 1
OUTPUT Number
ENDPROCEDURE
DECLARE FirstNumber : INTEGER
FirstNumber ← 5
CALL Show(FirstNumber)
OUTPUT FirstNumber
BYREF passes the real variable
BYREFmeans the parameter is the caller's variable. A change is still there afterCALL.- A mode keyword continues across later parameters until another mode keyword changes it.
BYREF FirstValue : INTEGER, SecondValue : INTEGERmakes both parameters references. - Do not pass a parameter to a function by reference. Use
BYREFon a procedure.
PROCEDURE Swap(BYREF FirstValue : INTEGER, BYREF SecondValue : INTEGER)
DECLARE Temp : INTEGER
Temp ← FirstValue
FirstValue ← SecondValue
SecondValue ← Temp
ENDPROCEDURE
DECLARE FirstNumber : INTEGER
DECLARE SecondNumber : INTEGER
FirstNumber ← 1
SecondNumber ← 2
CALL Swap(FirstNumber, SecondNumber)
OUTPUT FirstNumber, ",", SecondNumber
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.
Independent transfer
The final task has no supplied algorithm. Plan its inputs, processing and outputs, then solve it before opening support. Check more than the sample case.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write a procedure Greet with no parameters that outputs Hi, then CALL it.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write Swap so that BYREF exchanges FirstNumber and SecondNumber. Start from FirstNumber ← 1 and SecondNumber ← 2, and output 2,1.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write only PROCEDURE Reduce(BYREF Amount : INTEGER, BYVAL Discount : INTEGER). Reduce Amount by Discount, but never below zero. The checker calls it.
Click Run to see the output here.