You are on page 1of 24

Pass-by-Value & Pass-by-reference

Programming fundamentals - part 03/04


1.
Two ”variables”, one “value”
What’s “really” happen in the following code:
what’s “value” will be displayed and why ?
First, the 7 “value” is
put inside the X “variable”
Next, the same 7 “value” is put inside the Y “variable”
The X & Y variables share the same value !!!
Y is an “ALIAS” of X.
Next, the 7 “value” of the X “variable” is replaced by the
8 “value”. But don’t forget they share the same value.
So in the end, it displays the 8 “value”
2.
Pass by ”Value” vs BY ”Reference”
Are you “sure” the 3rd line will display “eric” ?
The good answer is “No”

It depends the sayHello function… if the “variable” is


pass by value or by reference.
3.
Pass by ”Value” (also called pass by “copy”)
Let’s look the standard case: Passing-by-Value.
First, the “eric” “value” is put into the name “variable”.
Next, the “eric” “value” is copied into the who “variable”.
Next, “Hello eric\n” “value” is put into the who “variable”.
Next, the “value” of the who “variable” is displayed.
End, the “value” of the name “variable” is displayed.
4.
Pass by ”Reference”
Let’s look the other case: Passing-by-Reference.
First, the “eric” “value” is put into the name “variable”.
Next, the same “eric” “value” is put into the who “variable”
Next, the “eric” “value” of the who “variable” is replaced by
the “Hello eric\n” “value”. Don’t forget this value is shared.
Next, the “value” of the who “variable” is displayed.
Next, the “value” of the name “variable” is displayed.
As the value is shared… so it displays the same thing.

You might also like