Parameter Passing

Parameters

A  parameter is a variable or value that is passed into and/or out of a subprogram.  There are two types of parameters.

  • The formal parameters are used in the subprogram definition
  • The actual parameters are passed into the subprogram when the subprogram is called.

  • Formal parameters contains the pointer/address of actual parameters .
  • Any changes to the formal parameters are automatically made to the actual parameter.

Passing Parameters by Reference  and by Value

Parameter Passing by Reference

Parameter passing by reference is used  when the value being passed in is to be updated and passes back out again. (The variable itself is passed into the subprogram so that any changes to the variable will change the variable.

If a programmer passes a parameter by reference, then the subprogram or function has direct access to the memory location holding the value of the variable.

This means that any change to the value during the execution of the subprogram would apply when the variable was next used in the main program.

Parameter Passing by Value

Parameter passing by value is used  when a value is passed into a subprogram but does not require to be passed out. (The subprogram makes a copy of the variable so that any changes to the copy of the variable will not change the variable.

If a programmer passes a parameter by value, then a temporary second copy of the value of the variable is made and held in RAM.

This copy can be changed within a subprogram but the change would not affect the original value held in the main program’s local variable.

Drawback

The main drawback is the increased demand on RAM.  As well as having to store the original value of the local variable, it is also necessary to store a second copy in main memory as well.

Advantage

The main advantage is that the value of the original local variable is protected from accidental or unnecessary change.