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 a placeholder for the actual parameter
  • The actual parameters are the values passed into the subprogram

  • Formal parameters contains the placeholder of the actual parameters .
  • Any changes to the formal parameters are automatically made to the actual parameter.
  • The Actual parameters contain the value

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.