Call by reference is a way of passing arguments (or 'parameters') to functions
(or 'procedures', or 'subroutines', or whatever your programming language designers chose to call them). Instead of passing the value itself, a reference to the value is passed. As a consequence, the value can be modified from within the subroutine (or 'function', or 'procedure'). Also, if values can be large (like, a 100M blob of binary data), it is significantly cheaper than call by value.

Call-by-reference is a way to pass an object as a parameter to a function, in a way that you can change the object and not worry about doing other bad things. Only a few languages implement call-by-reference properly; the best known are Pascal (/Delphi) and C++. C++. of course, came upon pass-by-reference belatedly, when Bjarne Stroustrup added "references" to the language.

Pascal syntax:


procedure foo (var bar: bar_type);

begin
bar := some_value;
end;

C++ syntax:


void foo (bar_type &bar)
{
 bar = some_value;
}

C++ also lets you pass a parameter by const reference:

void foo (bar_type const &bar);
but this is usually just a more efficient form of call by value.

Since C has nothing like references, the best you can do is pass in a pointer to the object:


void foo (bar_type *bar)
{
 *bar = some_value;
}
but of course you can do something like this without realizing it:

void foo (bar_type *bar)
{
 free (bar);
}

...

bar_type bar;

foo (&bar);  /* BOOM! */

A lot of people have problems with call-by-reference; the only reason I can think of for this is that they don't understand the semantics of references.

Despite the fact that Bjarne Stroustrup himself discourages passing parameters into C++ functions by non-const reference, it is really the best way to have modifiable parameters in that language.

This resistance reflects the habits of C programmers just learning C++. The usual argument is, "That little & in a function argument tells me it is likely to change! I don't have time to go digging into header files, how else am I going to know?"

The answer to that is, "Don't go modifying code if you don't understand how it works". I'd like someone to tell me how seeing an & would keep you from doing the bad thing I illustrated above. Take the time to dig into the header, or better yet, read the documentation for the function.

In other languages, you can rebind references1! In those languages, "reference" is really just a codeword for "pointer". Now we're back to the C situation given above, or some analogue. Tricky, indeed.

Repeat after me: Call by reference is a Good Thing.


1That is, without triggering undefined behavior. In C++ you can create the following monstrosity:

  union {
         bar &r;
         bar *p;
        } foo;

  bar b;

  foo.r = b;
  delete foo.p; // BOOM!
but this is a lot of work for the sole reason of being perverse; don't do that.

Log in or registerto write something here or to contact authors.