Call by reference

From Wiki @ Karl Jones dot com
Revision as of 16:16, 24 September 2016 by Karl Jones (Talk | contribs)

Jump to: navigation, search

In computer programming, call by reference (also referred to as pass by reference) is an evaluation strategy where a function receives an implicit reference to a variable used as argument, rather than a copy of its value.

Description

This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller. Call by reference can therefore be used to provide an additional channel of communication between the called function and the calling function.

A call-by-reference language makes it more difficult for a programmer to track the effects of a function call, and may introduce subtle software defects.

Many languages support call by reference in some form or another, but comparatively few use it as a default. FORTRAN II is an early example of a call-by-reference language. A few languages, such as C++, PHP, Visual Basic .NET, C# and REALbasic, default to call by value, but offer special syntax for call-by-reference parameters. C++ additionally offers call by reference to const.

Call by reference can be simulated in languages that use call by value and don't exactly support call by reference, by making use of references (objects that refer to other objects), such as pointers (objects representing the memory addresses of other objects). Languages such as C and ML use this technique. It is not a separate evaluation strategy—the language calls by value—but sometimes it is referred to as call by address (also referred to as pass by address). In an unsafe language like C this may cause memory safety errors such as null pointer dereferences, and also may be confusing. In ML references are type- and memory- safe.

Similar effect is achieved by call by sharing (passing an object, which can then be mutated), used in languages like Java, Python, and Ruby.

In purely functional languages there is typically no semantic difference between the two strategies (since their data structures are immutable, so there is no possibility for a function to modify any of its arguments), so they are typically described as call by value even though implementations frequently use call by reference internally for the efficiency benefits.

See also

External links