well, there debate on below code between me , friend. we're bit confused output produce. can clarify call-by-reference , call-by value result below piece of code?
program params; var i: integer; a: array[1..2] of integer; procedure p(x,y: integer); begin x := x + 1; := + 1; y := y + 1; end; begin a[1] := 1; a[2] := 2; := 1; p( a[i],a[i] ); output( a[1],a[2] ); end.
the resulting output of program in case parameters transmitted procedure p value-result , reference.
call value
x
, y
in p
local variables initialized actual parameters, while i
global variable, call p( a[i],a[i] )
equivalent to:
x := 1 /* value of a[i] */ y := 1 /* value of a[i] */ x := 2 /* x + 1 */ := 2 /* + 1 */ y := 2 /* y + 1 */
and @ end values 1, 2 printed since values of a[1]
, a[2]
weren't changed.
call reference
both x
, y
in p
alias a[1]
, (again) a[1]
(since i = 1
when procedure called), call equivalent to:
a[1] := 2 /* a[1] + 1 */ := 2 /* + 1 */ a[1] := 3 /* a[1] + 1 */
and @ end values 3, 2 printed.
call name
call name equivalent call reference when simple variables passed parameters, different when pass expression denotes memory location, subscript. in case actual parameter re-evaluated each time encountered. in case, effect of call of p( a[i],a[i] )
:
a[1] := 2 /* since = 1, result equal a[1] + 1 */ := 2 /* + 1 */ a[2] := 3 /* since 2, result equal a[2] + 1 */
and @ end values 2, 3 printed. in practice implementation calls anonymous function (a “thunk”), each time must evaluate parameter.
call value result
just complete discussion, here case value-result parameter passing, in x
, y
initialized @ beginning of procedure execution values of actual parameters, and, @ end of execution of procedure, copied original variables addresses:
x := 1 /* value of a[i] */ y := 1 /* value of a[i] */ x := 2 /* x + 1 */ := 2 /* + 1 */ y := 2 /* y + 1 */ a[1] := 1 /* value of x copied a[1] */ a[1] := 2 /* value of y copied a[1] (not a[2]!) */
and @ end values 2, 2 printed.
for discussion of different ways of passing parameters, see instance this.
Comments
Post a Comment