Question 1 Report
Study the following two implementations of the same task: doubling a number.
PROCEDURE DoubleProc(BYREF Value : INTEGER)
Value ← Value * 2
ENDPROCEDURE
FUNCTION DoubleFunc(Value : INTEGER) RETURNS INTEGER
RETURN Value * 2
ENDFUNCTION
DECLARE X : INTEGER
DECLARE Y : INTEGER
X ← 5
Y ← DoubleFunc(X)
OUTPUT X, " ", Y
CALL DoubleProc(X)
OUTPUT X(a) State the three output values. [3]
(b) Explain why X is unchanged after calling DoubleFunc but changed after calling DoubleProc. [2]
(c) Give one situation where the procedure version would be preferred, and one where the function version would be preferred. [2]
(d) State whether DoubleFunc uses pass by value or pass by reference. [1]
(a) The three output values demonstrate the difference between pass by value and pass by reference: [3]
5 10 - X is unchanged at 5, and Y receives the return value DoubleFunc(5) = 10. [1]10 - X is doubled to 10 by DoubleProc, which uses BYREF. [2](b) DoubleFunc passes X by value (a copy is made), so the original X remains 5. The doubled result is returned and stored in Y. [1] DoubleProc passes X by reference (BYREF), so the procedure directly modifies the original variable X, changing it from 5 to 10. [1]
(c) The procedure version is preferred when you want to modify the original variable directly, such as updating a balance in-place. [1] The function version is preferred when you need to use the result in an expression or assignment without changing the original, such as calculating a display value while keeping source data intact. [1]
(d) DoubleFunc uses pass by value. The parameter does not have the BYREF keyword, so a copy of the argument is made when the function is called. [1]
Everything you need to excel in your exams