The difference between pass-by-value and pass-by-reference (also known as "call-by-value" and "call-by-reference" respectively) is most easily explained using the following pseudocode.
function modify(input) { input = "red" } var x = "blue" modify(x) print(x) // "blue" indicates `x` was passed by value // "red" indicates `x` was passed by reference
Hint: almost all popular programming languages pass by value, at least by default. This includes C, C++, Java, JavaScript, Python, PHP and Visual Basic .NET. The most notable exception is Perl.
Some programming languages allow you to pass by reference if you use special syntax. This includes C++, C#, PHP and Visual Basic .NET.
When x
is an object, many pass-by-value programming languages pass an object reference as their value.
Use this pseudocode to test this behaviour.
function modify(input) { input.colour = "red" } var x = {colour : "blue"} modify(x) print(x.colour) // "blue" if whole object `x` was passed by value // "red" if reference to object `x` was passed by value // "red" if `x` was passed by reference
Hint: almost all popular pass-by-value programming languages pass an object reference as their value. This includes Java, JavaScript and Python. A notable exception is C++.
That's it. Now you know the whole story.
Discussion (12)
2013-06-17 19:30:06 by qntm:
2013-06-17 19:41:22 by AliceOMeta:
2013-06-17 19:46:39 by qntm:
2013-06-17 20:29:09 by David:
2013-06-17 22:40:33 by Ian:
2013-06-18 06:43:09 by skztr:
2013-06-18 10:52:50 by qntm:
2013-06-18 18:18:07 by bdew:
2013-06-18 20:09:56 by qntm:
2013-06-25 02:57:21 by KimikoMuffin:
2013-07-26 23:20:33 by JonSkeet:
2015-05-24 21:10:35 by anonymous: