Parameters

Parameters are what make subroutines useful. They are a means of passing information to a subroutine

Subroutines should be designed to be as 'self-contained' as possible. This means that they should not rely on variables or results from other subroutines - and they do not use variables declared globally if it can be avoided. The interface of a subroutine should only be through its parameters.

A well-designed subroutine should be capable of being used in programs other than the one for which it was originally designed.

 

Parameter passing...can be

  • by value
  • by reference

Example 1 (by value): A procedure which draws a line of dashes.

procedure Drawline(n : integer);
var i : integer;
begin
    for i := 1 to n do
         output('-');
    output(new line);
end;
n is the parameter - the number of dashes to be drawn in the line.

i is a local variable used in the subroutine to control the loop.

The procedure can be called by passing a value to it which is stored as the value of parameter n, and is used when the procedure is run. Eg Drawline(20) would pass the value 20 to the parameter n.

Or Drawline(x) would pass the value of a variable x to the parameter n.

Example 2 (by reference): A procedure which converts a number of days into weeks and days.

procedure ToWeeks(Total : integer;
                                    var weeks, days : integer);
begin
    weeks := total div 7;
    days := total mod 7;
end;
The two parameters weeks and days are variable parameters. The addresses of two variables must be  passed to the procedure.
The procedure is called by passing a value and two variables (whose values are altered when the procedure is run). Eg ToWeeks(30,w,d) would change the value of w to 4 and d to 2.

 

Exercise

Question : Why could we not write the ToWeeks procedure as a function?

Answer : (click on box to reveal)