Parameter Passing

From Rosetta Code
(Redirected from Parameter passing)

Parameters of a subprogram refer to its arguments and results. 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 (the identifier of the parameter) is distinct from the object of the actual parameter (the value that has been passed in). In particular, the formal parameter has an independent set of states, so that if the object is mutable, then updates to the object do not influence the state of the actual parameter object, so long as the program has not left the subprogram.

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's choices of parameter passing modes may vary greatly, as the following examples show.

Example Ada[edit]

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

  • objects of the scalar types are passed by value
  • objects with an identity are passed by reference. Objects with identities are 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++[edit]

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

Example Fortran[edit]

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

Starting from Fortran 90 (and later), functions and subroutines can specify an intent for the argument; intent can be: in (unmodificable argument), out (argument used to return a value; the starting value must be intended not significative, undefined), inout (argument both is intended for input and can be modified, i.e. return the value modified by the function/subroutine).

Trying to modify an argument with intent in triggers an error at compile time.