Programming – Pascal: Essential skills 6
Learning Outcomes:
- Implement parameters passing in manipulating sub-programs.
- The sub-programs are called by two parameters passing methods: call by value and call by reference.
Call-by-value/Call-by-reference
When using procedure or function, parameters may be passed into
the called procedure / function. The original parameters may or may not be
affected depending on call-by-value or call-by-reference.
Call-by-value:
var x, y
: integer; (* global variables *) procedure add (a, b : integer); (* a and b have their own memory address *) begin a :=
a + 1; b :=
b + 1; write
(a+b) end; begin x :=
1; y :=
2; add
(x, y); (* the use of this
procedure does NOT affect the value of x and y *) write
(x + y) end. |
Output: 53
Call-by-reference:
(the only difference from the program above is the var in the procedure heading)
var x, y
: integer; (* global variables *) procedure add (var a, b :
integer); (* a and b uses
the memory address of x and y *) begin a :=
a + 1; (* x is now 2 *) b :=
b + 1; (* y is now 3 *) write
(a+b) end; begin x :=
1; y :=
2; add
(x, y); (* the use of this
procedure AFFECTS the values of x
and y *) write
(x + y) end. |
Output: 55
Procedure and function
While a procedure is a subprogram which is quite similar to
a usual program (see above), a function always returns a single result.
Procedure:
procedure add (a, b : integer); … |
Function:
function add (a, b : integer) :
integer; … |
Having the extra part (: integer), it means this function is
going to return an integer when called.
var x, y,
sum : integer; function add (a, b : integer) : integer; begin add
:= a + b end; begin x :=
1; y :=
2; sum
:= add (x, y); (* similar
to using a built-in function *) write
(sum) end. |
Output: 3
You can use call-by value or call-by-reference when using
functions depending on the purposes of the function / program.
Relevant past paper:
DSE ICT Elect B(SP-2017): SP 3d. PP 3a-d. 2012 3ac, 4ai.
CE CIT Elect A(2005-2011): 2009 4bii,iii.
No comments:
Post a Comment