Parameter Passing

From Rosetta Code
Revision as of 17:02, 25 July 2008 by rosettacode>Dmitry-kazakov (Created)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Parameters of a subprogram refer to its arguments and results of. A parameter can be passed in one of two modes:

  • by value (or else by copy)
  • by reference

When the parameter is passed by value within the subprogram the object denoted by the formal parameter is distinct from the object of the actual parameter. In particular, the formal parameter has an independent set of states, so that if the object is mutable, then updates of the object do not influence the state of the actual parameter object, so long the subprogram is not left.

When the parameter is passed by reference, the formal object represents an aliased view of the actual object. Thus updates of the formal object are instantly reflected by the actual object.

The mutability of the parameter is independent on the parameter passing mode. In general the formal parameter can have any of three access modes:

  • in (immutable)
  • out (update only, usually used for the results)
  • in-out (mutable)

For example, when an in-out parameter is passed by value, the compiler creates a copy of it and makes the copy available to the subprogram. After the subprogram completion, the value of the copy is written back to the actual object.

The language choice of parameter passing modes may greatly vary, as the following examples show.

Example Ada

Ada uses both by value and by reference passing and all three parameter access modes:

  • by value are passed objects of the scalar types;
  • by reference are passed objects with an identity. To them belong task types, protected types, non-copyable (limited) types, tagged types OO objects with type identity)
  • for all other types the choice is left to the compiler.

Example C/C++

C/C++ use only by value parameter passing. Arguments are mutable as if they were in-out. But the compiler does not stores the copies back. Results also passed by copy (copy out). Where by-reference passing is needed the C/C++ deploys referencential types T* and T& (in C++). So when an object of the type T need to be passed by reference, another object of either the type T* or T& is passed by value instead. Because in C++ objects can be automatically converted to the references to, in many cases the difference is not noticeable.

Example Fortran

Early versions of the language used only by reference parameter passing for the arguments.