Monday 11 November 2013

Call by value and Call by reference


Call by Value:When an argument is passed to a method, the invoked method gets a copy of the original value.Call by Reference also called call by Address is when a method receives an implicit reference of variable , not the value.
The reference of variable is stored in a pointer variable. Changes to the data pointed by the pointer are reflected in the data of the calling function. It is also known as Pass By Reference. This concept is a misunderstood concept in Java Programming
The difference between call-by-value and call-by-reference
The difference between call-by-value and call-by-reference (also known as "pass-by-value" and "pass-by-reference" respectively) is most easily explained using the following pseudocode.

x = "A"

function modify(input) {
            input = "B"
}

modify(x)
print(x) // "A" indicates language calls by value
         // "B" indicates language calls by reference
Hint: almost all popular programming languages call by value. This includes C, Java, Python and PHP. The most notable exception is Perl.

(Some programming languages allow you to call by reference if you use special syntax. This includes PHP and C#.)


Confusingly, many call-by-value programming languages pass an object reference as their value.

Use this pseudo code to test this behaviour.

x = new Object
x.colour = "white"

function modify(input) {
            input.colour = "black"
}

modify(x)
print(x.colour) // "white" if call-by-value and value is whole object
                // "black" if call-by-value and value is reference to object
                // "black" if call-by-reference
Hint: almost all popular call-by-value programming languages use a reference to the object as their value. This includes Java and Python.


No comments:

Post a Comment