-1
$\begingroup$

Can someone explain to me in a plain English what call by Reference mean ? I am having trouble to recognize a difference between "call by value" and "call by reference"

Thank you.

$\endgroup$
1
  • 2
    $\begingroup$ What part of the Wikipedia article are you having trouble with? $\endgroup$ – Gilles 'SO- stop being evil' Feb 23 '17 at 18:43
3
$\begingroup$

When you call a function, it gets the arguments.

In math, as well as "pure" functional languages, the function can look at those arguments and compute things based on them, then return a result.

The complication comes from how, in most languages, computation can have side-effects: variables can have their values changed (mutated).

So, for example, if I pass a record/struct to a function and change one of its values, then look at the record after the function has returned, do I still see the changes?

The answer is yes for call by reference, and no for call by value.

Consider the following pseudocode:

function foo(bar):
  bar.x = 3
  return bar.x + bar.y

function main:
  myrecord = {x:1, y:2}
  myval = foo(myrecord)
  print myrecord.x

What does this program print? 1, or 3?

In call by reference, it prints 3. The function foo works on the same piece of memory that main works on, so any changes it makes, main sees.

In call by value, it prints 1. The "value" of myrecord is passed to foo, namely a record with 1 and 2 as its fields, but they're not operating on the same piece of memory, so main doesn't see any of the changes foo makes, because foo was just seeing a copy of myrecord.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.