Search code examples
memory-managementparameter-passingcomputer-science

What is the difference between call-by-reference and call-by-value-return


As the title says I'm curious about the difference between "call-by-reference" and "call-by-value-return". I've read about it in some literature, and tried to find additional information on the internet, but I've only found comparison of "call-by-value" and "call-by-reference".

I do understand the difference at memory level, but not at the "conceptual" level, between the two.

The called subroutine will have it's own copy of the actual parameter value to work with, but will, when it ends executing, copy the new local value (bound to the formal parameter) back to the actual parameter of the caller.

When is call-by-value-return actually to prefer above "call-by-reference"? Any example scenario? All I can see is that it takes extra memory and execution time due to the copying of values in the memory-cells.

As a side question, is "call-by-value-return" implemented in 'modern' languages?


Solution

  • Call-by-value-return, from Wikipedia:

    This variant has gained attention in multiprocessing contexts and Remote procedure call: if a parameter to a function call is a reference that might be accessible by another thread of execution, its contents may be copied to a new reference that is not; when the function call returns, the updated contents of this new reference are copied back to the original reference ("restored").

    So, in more practical terms, it's entirely possible that a variable is in some undesired state in the middle of the execution of a function. With parallel processing this is a problem, since you can attempt to access the variable while it has this value. Copying it to a temporary value avoids this problem.

    As an example:

    policeCount = 0
    
    everyTimeSomeoneApproachesOrLeaves()
      calculatePoliceCount(policeCount)
    
    calculatePoliceCount(count)
      count = 0
      for each police official
        count++
    
    goAboutMyDay()
      if policeCount == 0
        doSomethingIllegal()
      else
        doSomethingElse()
    

    Assume everyTimeSomeoneApproachesOrLeaves and goAboutMyDay are executed in parallel.

    So if you pass by reference, you could end up getting policeCount right after it was set to 0 in calculatePoliceCount, even if there are police officials around, then you'd end up doing something illegal and probably going to jail, or at least coughing up some money for a bribe. If you pass by value return, this won't happen.

    Supported languages?

    In my search, I found that Ada and Fortran support this. I don't know of others.