CAIE 0478 & 9618
Subroutines
8. Procedures & Functions
Modular Cambridge pseudocode subroutines: PROCEDURE with CALL, FUNCTION with RETURN, and parameter passing by value (BYVAL) and reference (BYREF).
Procedures perform actions and are invoked with CALL. Functions return a single value via RETURN and are called as part of an expression (not with CALL). IGCSE uses ordinary typed parameters. Explicit pass-by-value (BYVAL, default) and pass-by-reference (BYREF) modes are AS & A Level (9618) extensions.
Procedures (CALL)
PSEUDOCODE
// Without parameters
PROCEDURE DefaultSquare()
CALL Square(100)
ENDPROCEDURE
// With parameters
PROCEDURE Square(Size : INTEGER)
FOR Side <- 1 TO 4
CALL MoveForward(Size)
CALL Turn(90)
NEXT Side
ENDPROCEDURE
CALL Square(50)
Functions (RETURN)
PSEUDOCODE
FUNCTION Max(Number1 : INTEGER,
Number2 : INTEGER)
RETURNS INTEGER
IF Number1 > Number2 THEN
RETURN Number1
ELSE
RETURN Number2
ENDIF
ENDFUNCTION
// Called as part of an expression
OUTPUT "Penalty = ", Max(10, Distance*2)
Passing by Reference (BYREF)
PSEUDOCODE
// BYREF allows the procedure to modify the caller's variables directly
PROCEDURE SWAP(BYREF X : INTEGER, BYREF Y : INTEGER)
Temp <- X
X <- Y
Y <- Temp
ENDPROCEDURE
// Note: If not specified, BYVAL (pass by value) is assumed.
// Parameters should NOT be passed BYREF to a function.