<p>When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, <em>pass-by-value or pass-by-reference</em>.</p>

<p>So here is my question to all of you, in your favorite language, <em>how</em> is it actually done? And what are the <em>possible pitfalls</em>?</p>

<p>Your favorite language can, of course, be anything you have ever played with: <a href="http://www.ruby-lang.org/en/" rel="noreferrer">popular</a>, <a href="http://www.devtopics.com/a-obscure-programming-language-of-the-month/" rel="noreferrer">obscure</a>, <a href="http://en.wikipedia.org/wiki/Brainfuck" rel="noreferrer">esoteric</a>, <a href="http://www.nvidia.com/object/cuda_get.html" rel="noreferrer">new</a>, <a href="http://en.wikipedia.org/wiki/FORTRAN" rel="noreferrer">old</a>...</p>

[{'answer_id': 2028, 'author': 'sven', 'author_id': 46, 'author_profile': 'https://Stackoverflow.com/users/46', 'pm_score': 5, 'selected': False, 'text': '<p>Here is my own contribution for the <a href="http://en.wikipedia.org/wiki/Java_(programming_language)" rel="nofollow noreferrer">Java programming language</a>.</p>\n\n<p>first some code:</p>\n\n<pre><code>public void swap(int x, int y)\n{\n  int tmp = x;\n  x = y;\n  y = tmp;\n}\n</code></pre>\n\n<p>calling this method will result in this:</p>\n\n<pre><code>int pi = 3;\nint everything = 42;\n\nswap(pi, everything);\n\nSystem.out.println("pi: " + pi);\nSystem.out.println("everything: " + everything);\n\n"Output:\npi: 3\neverything: 42"\n</code></pre>\n\n<p>even using \'real\' objects will show a similar result:</p>\n\n<pre><code>public class MyObj {\n    private String msg;\n    private int number;\n\n    //getters and setters\n    public String getMsg() {\n        return this.msg;\n    }\n\n\n    public void setMsg(String msg) {\n        this.msg = msg;\n    }\n\n\n    public int getNumber() {\n        return this.number;\n    }\n\n\n    public void setNumber(int number) {\n        this.number = number;\n    }\n\n    //constructor\n    public MyObj(String msg, int number) {\n        setMsg(msg);\n        setNumber(number);\n    }\n}\n\npublic static void swap(MyObj x, MyObj y)\n{\n    MyObj tmp = x;\n    x = y;\n    y = tmp;\n}\n\npublic static void main(String args[]) {\n    MyObj x = new MyObj("Hello world", 1);\n    MyObj y = new MyObj("Goodbye Cruel World", -1); \n\n    swap(x, y);\n\n    System.out.println(x.getMsg() + " -- "+  x.getNumber());\n    System.out.println(y.getMsg() + " -- "+  y.getNumber());\n}\n\n\n"Output:\nHello world -- 1\nGoodbye Cruel World -- -1"\n</code></pre>\n\n<p>thus it is clear that Java passes its parameters <strong>by value</strong>, as the value for <em>pi</em> and <em>everything</em> and the <em>MyObj objects</em> aren\'t swapped.\nbe aware that "by value" is the <em>only way</em> in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using \'<strong>&amp;</strong>\' after the parameter\'s type)</p>\n\n<p>now the <strong>tricky part</strong>, or at least the part that will confuse most of the new java developers: (borrowed from <a href="http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html" rel="nofollow noreferrer">javaworld</a>)<br>\nOriginal author: Tony Sintes</p>\n\n<pre><code>public void tricky(Point arg1, Point arg2)\n{\n    arg1.x = 100;\n    arg1.y = 100;\n    Point temp = arg1;\n    arg1 = arg2;\n    arg2 = temp;\n}\npublic static void main(String [] args)\n{\n    Point pnt1 = new Point(0,0);\n    Point pnt2 = new Point(0,0);\n    System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); \n    System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);\n    System.out.println(" ");\n    tricky(pnt1,pnt2);\n    System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); \n    System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);  \n}\n\n\n"Output\nX: 0 Y: 0\nX: 0 Y: 0\nX: 100 Y: 100\nX: 0 Y: 0"\n</code></pre>\n\n<p><em>tricky</em> successfully changes the value of pnt1!\nThis would imply that Objects are passed by reference, this is not the case!\nA correct statement would be: <strong>the <em>Object references</em> are passed by value.</strong>  </p>\n\n<p>more from Tony Sintes:  </p>\n\n<blockquote>\n  <p>The method successfully alters the\n  value of pnt1, even though it is\n  passed by value; however, a swap of\n  pnt1 and pnt2 fails! This is the major\n  source of confusion. In the main()\n  method, pnt1 and pnt2 are nothing more\n  than object references. When you pass\n  pnt1 and pnt2 to the tricky() method,\n  Java passes the references by value\n  just like any other parameter. This\n  means the references passed to the\n  method are actually copies of the\n  original references. Figure 1 below\n  shows two references pointing to the\n  same object after Java passes an\n  object to a method.</p>\n</blockquote>\n\n<p><a href="https://i.stack.imgur.com/EXPyo.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EXPyo.gif" alt="figure 1"></a><br>\n<sub>(source: <a href="http://www.javaworld.com/javaworld/javaqa/2000-05/images/03-qa-0512-pass2b.gif" rel="nofollow noreferrer">javaworld.com</a>)</sub>  </p>\n\n<p><strong>Conclusion</strong> or a long story short:</p>\n\n<ul>\n<li>Java passes it parameters <strong>by value</strong></li>\n<li><em>"by value"</em> is the <strong>only way</strong> in java to pass a parameter to a method</li>\n<li>using <em>methods from the object</em> given as parameter <strong>will alter</strong> the object as the references point to the original objects. (if that method itself alters some values)</li>\n</ul>\n\n<p>useful links:  </p>\n\n<ul>\n<li><a href="http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html</a></li>\n<li><a href="http://www.ibm.com/developerworks/java/library/j-passbyval/" rel="nofollow noreferrer">http://www.ibm.com/developerworks/java/library/j-passbyval/</a></li>\n<li><a href="http://www.ibm.com/developerworks/library/j-praxis/pr1.html" rel="nofollow noreferrer">http://www.ibm.com/developerworks/library/j-praxis/pr1.html</a></li>\n<li><a href="http://javadude.com/articles/passbyvalue.htm" rel="nofollow noreferrer">http://javadude.com/articles/passbyvalue.htm</a></li>\n</ul>\n'}, {'answer_id': 2033, 'author': 'DShook', 'author_id': 370, 'author_profile': 'https://Stackoverflow.com/users/370', 'pm_score': 2, 'selected': False, 'text': '<p><strong>by value</strong> </p>\n\n<ul>\n<li>is slower than by reference since the system has to copy the parameter</li>\n<li>used for input only  </li>\n</ul>\n\n<p><strong>by reference</strong></p>\n\n<ul>\n<li>faster since only a pointer is passed</li>\n<li>used for input <strong>and</strong> output</li>\n<li>can be very dangerous if used in conjunction with global variables</li>\n</ul>\n'}, {'answer_id': 2051, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 3, 'selected': False, 'text': '<p>Don\'t forget there is also <strong>pass by name</strong>, and <strong>pass by value-result</strong>.</p>\n\n<p>Pass by value-result is similar to pass by value, with the added aspect that the value is set in the original variable that was passed as the parameter.  It can, to some extent, avoid interference with global variables.  It is apparently better in partitioned memory, where a pass by reference could cause a page fault (<a href="http://logos.cs.uic.edu/476/notes/PassByRefOrValResult.html" rel="noreferrer">Reference</a>).</p>\n\n<p>Pass by name means that the values are only calculated when they are actually used, rather than at the start of the procedure.  Algol used pass-by-name, but an interesting side effect is that is it very difficult to write a swap procedure (<a href="http://www.cs.sfu.ca/~cameron/Teaching/383/PassByName.html" rel="noreferrer">Reference</a>).  Also, the expression passed by name is re-evaluated each time it is accessed, which can also have side effects.</p>\n'}, {'answer_id': 2554, 'author': 'sven', 'author_id': 46, 'author_profile': 'https://Stackoverflow.com/users/46', 'pm_score': 4, 'selected': False, 'text': '<p>Here is another article for the <a href="http://msdn.microsoft.com/en-us/vcsharp/default.aspx" rel="nofollow noreferrer">c# programming language</a></p>\n\n<p>c# passes its arguments <strong>by value</strong> (by default)</p>\n\n<pre><code>private void swap(string a, string b) {\n  string tmp = a;\n  a = b;\n  b = tmp;\n}\n</code></pre>\n\n<p>calling this version of swap will thus have no result:</p>\n\n<pre><code>string x = "foo";\nstring y = "bar";\nswap(x, y);\n\n"output: \nx: foo\ny: bar"\n</code></pre>\n\n<p>however, <a href="https://stackoverflow.com/questions/2027/#2028">unlike java</a> c# <em>does</em> give the developer the opportunity to pass parameters <strong>by reference</strong>, this is done by using the \'ref\' keyword before the type of the parameter:</p>\n\n<pre><code>private void swap(ref string a, ref string b) {\n  string tmp = a;\n  a = b;\n  b = tmp;\n} \n</code></pre>\n\n<p>this swap <em>will</em> change the value of the referenced parameter:</p>\n\n<pre><code>string x = "foo";\nstring y = "bar";\nswap(x, y);\n\n"output: \nx: bar\ny: foo"\n</code></pre>\n\n<p>c# also has a <strong>out keyword</strong>, and the difference between ref and out is a subtle one.\n<a href="http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx" rel="nofollow noreferrer">from msdn:</a></p>\n\n<blockquote>\n  <p>The caller of a method which takes an\n  <strong>out parameter</strong> is not required to\n  assign to the variable passed as the\n  out parameter prior to the call;\n  however, the callee is <em>required to\n  assign to the out parameter before\n  returning.</em></p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n  <p>In contrast <strong>ref parameters</strong> are\n  <em>considered initially assigned</em> by the\n  callee. As such, the callee is <em>not\n  required to assign to the ref</em>\n  parameter before use. Ref parameters\n  are passed both into and out of a\n  method.</p>\n</blockquote>\n\n<p>a small pitfall is, like in java, that <strong>objects passed by value can still be changed using their inner methods</strong></p>\n\n<p><strong>conclusion:</strong> </p>\n\n<ul>\n<li>c# passes its parameters, by default, <strong>by value</strong> </li>\n<li>but when needed parameters can also be passed <strong>by reference</strong> using the ref keyword</li>\n<li>inner methods from a parameter passed by value <strong>will alter</strong> the object (if that method itself alters some values)</li>\n</ul>\n\n<p>useful links:</p>\n\n<ul>\n<li><a href="http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx</a></li>\n<li><a href="http://www.c-sharpcorner.com/UploadFile/saragana/Willswapwork11162005012542AM/Willswapwork.aspx" rel="nofollow noreferrer">http://www.c-sharpcorner.com/UploadFile/saragana/Willswapwork11162005012542AM/Willswapwork.aspx</a></li>\n<li><a href="http://en.csharp-online.net/Value_vs_Reference" rel="nofollow noreferrer">http://en.csharp-online.net/Value_vs_Reference</a></li>\n</ul>\n'}, {'answer_id': 4078, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s a <a href="http://codebetter.com/blogs/karlseguin/archive/2008/04/27/foundations-of-programming-pt-7-back-to-basics-memory.aspx" rel="noreferrer">good explanation here</a> for .NET.</p>\n\n<p>A lot of people are surprise that reference objects are actually passed by value (in both C# and Java). It\'s a copy of a stack address. This prevents a method from changing where the object actually points to, but still allows a method to change the values of the object. In C# its possible to pass a reference by reference, which means you can change where an actual object points to.</p>\n'}, {'answer_id': 7485, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 2, 'selected': False, 'text': '<p>PHP is also pass by value.</p>\n\n<pre><code>&lt;?php\nclass Holder {\n    private $value;\n\n    public function __construct($value) {\n        $this-&gt;value = $value;\n    }\n\n    public function getValue() {\n        return $this-&gt;value;\n    }\n}\n\nfunction swap($x, $y) {\n    $tmp = $x;\n    $x = $y;\n    $y = $tmp;\n}\n\n$a = new Holder(\'a\');\n$b = new Holder(\'b\');\nswap($a, $b);\n\necho $a-&gt;getValue() . ", " . $b-&gt;getValue() . "\\n";\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>a b\n</code></pre>\n\n<p>However in PHP4 objects were treated like <a href="http://www.php.net/manual/en/migration5.oop.php" rel="nofollow noreferrer">primitives</a>. Which means:</p>\n\n<pre><code>&lt;?php\n$myData = new Holder(\'this should be replaced\');\n\nfunction replaceWithGreeting($holder) {\n    $myData-&gt;setValue(\'hello\');\n}\n\nreplaceWithGreeting($myData);\necho $myData-&gt;getValue(); // Prints out "this should be replaced"\n</code></pre>\n'}, {'answer_id': 24370, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Python</strong> uses pass-by-value, but since all such values are object references, the net effect is something akin to pass-by-reference. However, Python programmers think more about whether an object type is <em>mutable</em> or <em>immutable</em>. Mutable objects can be changed in-place (e.g., dictionaries, lists, user-defined objects), whereas immutable objects can\'t (e.g., integers, strings, tuples).</p>\n\n<p>The following example shows a function that is passed two arguments, an immutable string, and a mutable list.</p>\n\n<pre><code>&gt;&gt;&gt; def do_something(a, b):\n...     a = "Red"\n...     b.append("Blue")\n... \n&gt;&gt;&gt; a = "Yellow"\n&gt;&gt;&gt; b = ["Black", "Burgundy"]\n&gt;&gt;&gt; do_something(a, b)\n&gt;&gt;&gt; print a, b\nYellow [\'Black\', \'Burgundy\', \'Blue\']\n</code></pre>\n\n<p>The line <code>a = "Red"</code> merely creates a local name, <code>a</code>, for the string value <code>"Red"</code> and has no effect on the passed-in argument (which is now hidden, as <code>a</code> must refer to the local name from then on). Assignment is not an in-place operation, regardless of whether the argument is mutable or immutable.</p>\n\n<p>The <code>b</code> parameter is a reference to a mutable list object, and the <code>.append()</code> method performs an in-place extension of the list, tacking on the new <code>"Blue"</code> string value.</p>\n\n<p>(Because string objects are immutable, they don\'t have any methods that support in-place modifications.)</p>\n\n<p>Once the function returns, the re-assignment of <code>a</code> has had no effect, while the extension of <code>b</code> clearly shows pass-by-reference style call semantics.</p>\n\n<p>As mentioned before, even if the argument for <code>a</code> is a mutable type, the re-assignment within the function is not an in-place operation, and so there would be no change to the passed argument\'s value:</p>\n\n<pre><code>&gt;&gt;&gt; a = ["Purple", "Violet"]\n&gt;&gt;&gt; do_something(a, b)\n&gt;&gt;&gt; print a, b\n[\'Purple\', \'Violet\'] [\'Black\', \'Burgundy\', \'Blue\', \'Blue\']\n</code></pre>\n\n<p>If you didn\'t want your list modified by the called function, you would instead use the immutable tuple type (identified by the parentheses in the literal form, rather than square brackets), which does not support the in-place <code>.append()</code> method:</p>\n\n<pre><code>&gt;&gt;&gt; a = "Yellow"\n&gt;&gt;&gt; b = ("Black", "Burgundy")\n&gt;&gt;&gt; do_something(a, b)\nTraceback (most recent call last):\n  File "&lt;stdin&gt;", line 1, in &lt;module&gt;\n  File "&lt;stdin&gt;", line 3, in do_something\nAttributeError: \'tuple\' object has no attribute \'append\'\n</code></pre>\n'}, {'answer_id': 1776077, 'author': 'MPelletier', 'author_id': 210916, 'author_profile': 'https://Stackoverflow.com/users/210916', 'pm_score': 2, 'selected': False, 'text': '<p>Concerning <a href="http://www.jsoftware.com" rel="nofollow noreferrer">J</a>, while there is only, AFAIK, passing by value, there is a form of passing by reference which enables moving a lot of data. You simply pass something known as a locale to a verb (or function). It can be an instance of a class or just a generic container.</p>\n\n<pre><code>spaceused=: [: 7!:5 &lt;\nexectime =: 6!:2\nbig_chunk_of_data =. i. 1000 1000 100\npassbyvalue =: 3 : 0\n    $ y\n    \'\'\n)\nlocale =. cocreate\'\'\nbig_chunk_of_data__locale =. big_chunk_of_data\npassbyreference =: 3 : 0\n    l =. y\n    $ big_chunk_of_data__l\n    \'\'\n)\nexectime \'passbyvalue big_chunk_of_data\'\n   0.00205586720663967\nexectime \'passbyreference locale\'\n   8.57957102144893e_6\n</code></pre>\n\n<p>The obvious disadvantage is that you need to know the name of your variable in some way in the called function. But this technique can move a lot of data painlessly. That\'s why, while technically not pass by reference, I call it "pretty much that".</p>\n'}, {'answer_id': 4685077, 'author': 'oosterwal', 'author_id': 90695, 'author_profile': 'https://Stackoverflow.com/users/90695', 'pm_score': -1, 'selected': False, 'text': "<p>By default, ANSI/ISO C uses either--it depends on how you declare your function and its parameters.</p>\n\n<p>If you declare your function parameters as pointers then the function will be pass-by-reference, and if you declare your function parameters as not-pointer variables then the function will be pass-by-value.</p>\n\n<pre><code>void swap(int *x, int *y);   //&lt; Declared as pass-by-reference.\nvoid swap(int x, int y);     //&lt; Declared as pass-by-value (and probably doesn't do anything useful.)\n</code></pre>\n\n<p>You can run into problems if you create a function that returns a pointer to a non-static variable that was created within that function.  The returned value of the following code would be undefined--there is no way to know if the memory space allocated to the temporary variable created in the function was overwritten or not.</p>\n\n<pre><code>float *FtoC(float temp)\n{\n    float c;\n    c = (temp-32)*9/5;\n    return &amp;c;\n}\n</code></pre>\n\n<p>You could, however, return a reference to a static variable or a pointer that was passed in the parameter list.</p>\n\n<pre><code>float *FtoC(float *temp)\n{\n    *temp = (*temp-32)*9/5;\n    return temp;\n}\n</code></pre>\n"}, {'answer_id': 10143845, 'author': 'LeoNerd', 'author_id': 1069726, 'author_profile': 'https://Stackoverflow.com/users/1069726', 'pm_score': 3, 'selected': False, 'text': '<p>Since I haven\'t seen a Perl answer yet, I thought I\'d write one.</p>\n\n<p>Under the hood, Perl works effectively as pass-by-reference. Variables as function call arguments are passed referentially, constants are passed as read-only values, and results of expressions are passed as temporaries. The usual idioms to construct argument lists by list assignment from <code>@_</code>, or by <code>shift</code> tend to hide this from the user, giving the appearance of pass-by-value:</p>\n\n<pre><code>sub incr {\n  my ( $x ) = @_;\n  $x++;\n}\n\nmy $value = 1;\nincr($value);\nsay "Value is now $value";\n</code></pre>\n\n<p>This will print <code>Value is now 1</code> because the <code>$x++</code> has incremented the lexical variable declared within the <code>incr()</code> function, rather than the variable passed in. This pass-by-value style is usually what is wanted most of the time, as functions that modify their arguments are rare in Perl, and the style should be avoided.</p>\n\n<p>However, if for some reason this behaviour is specifically desired, it can be achieved by operating directly on elements of the <code>@_</code> array, because they will be aliases for variables passed into the function.</p>\n\n<pre><code>sub incr {\n  $_[0]++;\n}\n\nmy $value = 1;\nincr($value);\nsay "Value is now $value";\n</code></pre>\n\n<p>This time it will print <code>Value is now 2</code>, because the <code>$_[0]++</code> expression incremented the actual <code>$value</code> variable. The way this works is that under the hood <code>@_</code> is not a real array like most other arrays (such as would be obtained by <code>my @array</code>), but instead its elements are built directly out of the arguments passed to a function call. This allows you to construct pass-by-reference semantics if that would be required. Function call arguments that are plain variables are inserted as-is into this array, and constants or results of more complex expressions are inserted as read-only temporaries.</p>\n\n<p>It is however exceedingly rare to do this in practice, because Perl supports reference values; that is, values that refer to other variables. Normally it is far clearer to construct a function that has an obvious side-effect on a variable, by passing in a reference to that variable. This is a clear indication to the reader at the callsite, that pass-by-reference semantics are in effect.</p>\n\n<pre><code>sub incr_ref {\n  my ( $ref ) = @_;\n  $$ref++;\n}\n\nmy $value = 1;\nincr(\\$value);\nsay "Value is now $value";\n</code></pre>\n\n<p>Here the <code>\\</code> operator yields a reference in much the same way as the <code>&amp;</code> address-of operator in C.</p>\n'}, {'answer_id': 10147528, 'author': 'newacct', 'author_id': 86989, 'author_profile': 'https://Stackoverflow.com/users/86989', 'pm_score': 3, 'selected': False, 'text': '<p>Whatever you say as pass-by-value or pass-by-reference must be consistent across languages. The most common and consistent definition used across languages is that with pass-by-reference, you can pass a variable to a function "normally" (i.e. without explicitly taking address or anything like that), and the function can <em>assign to</em> (not mutate the contents of) the parameter inside the function and it will have the same effect as assigning to the variable in the calling scope.</p>\n\n<p>From this view, the languages are grouped as follows; each group having the same passing semantics. If you think that two languages should not be put in the same group, I challenge you to come up with an example that distinguishes them.</p>\n\n<p>The vast majority of languages including <strong>C</strong>, <strong>Java</strong>, <strong>Python</strong>, <strong>Ruby</strong>, <strong>JavaScript</strong>, <strong>Scheme</strong>, <strong>OCaml</strong>, <strong>Standard ML</strong>, <strong>Go</strong>, <strong>Objective-C</strong>, <strong>Smalltalk</strong>, etc. are all <strong>pass-by-value only</strong>. Passing a pointer value (some languages call it a "reference") does not count as pass by reference; we are only concerned about the thing passed, the pointer, not the thing pointed to.</p>\n\n<p>Languages such as <strong>C++</strong>, <strong>C#</strong>, <strong>PHP</strong> are by default pass-by-value like the languages above, but functions can explicitly declare parameters to be pass-by-reference, using <code>&amp;</code> or <code>ref</code>.</p>\n\n<p><strong>Perl</strong> is always pass-by-reference; however, in practice people almost always copy the values after getting it, thus using it in a pass-by-value way.</p>\n'}]
['https://Stackoverflow.com/questions/2027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46/']