A Comparison of Call-by-Value and Call-by-Reference

One of the more subtle distinctions in invoking functions is that of call-by-value vs. call-by reference.

Programming languages differ rather widely on which of these they support. Here are some specifics:

Language Parameter Passing Method Notes
COBOL Reference or Value Indicated by optional BY REFERENCE or BY VALUE keywords; default is BY REFERENCE
FORTRAN Reference  
Pascal Reference or Value Default is by value; by reference indicated by optional var keyword.
BASIC (Original) None; you couldn't pass parameters at all.  
Structured BASIC, c. 1987 Value  
Microsoft Visual BASIC 6.0 and earlier Reference or Value Indicated by optional ByRef or ByVal keywords; default is ByRef
Microsoft Visual BASIC.NET Reference or Value Indicated by optional ByRef or ByVal keywords; default is ByVal
C, C++ Value; but the effect of call by reference can be obtained through use of pointer variables.  
Java Value; HOWEVER when you declare a variable as having a class as its type, the variable is actually a reference to an object of that class, rather than the object itself as in C++. The reference is passed by value, with the practical effect that the object itself is called by reference.  

Please note that you are NOT expected to remember anything from the above table. It is presented here only to give you a feel for the extent of the variation among programming languages.

To help you understand the distinction, it would be good to have a real example in an actual programming language. To do this, we will have to use one of the languages that supports both. We will present a demonstration in the language Microsoft Visual BASIC.NET (VB.NET). The reasons for the choice are (1) it is not obsolete; in fact, VB.NET and earlier versions of Microsoft Visual BASIC are in wide use today; (2) the syntax of Visual BASIC is easy to understand, yet it is so different from C++ that there should be no risk of confusing the two languages.

The file ValueVsRefDemo.vb is a VB.NET program that illustrates this behavior. You should find it mostly self-explanatory. ValueVsRefDemoOutput.gif shows you some output that resulted from running the program. You should read through the main program (Sub Main), jumping to the invoked functions as needed, while following along in the output.