Parameters

A subroutine is a small sequence of instructions that is given an identifier (a name), and can be called (run) from anywhere in the main program.

When a subroutine is called from the main program, execution of the main program is halted. The code in the subroutine is run, and, when completed, the computer will return to carry on the main program where it left off.

Subroutines may be called frequently from the main program. Subroutines may call other subroutines.

The use of subroutines avoids repetitive code in a program.

There are two types of subroutine:

  • procedures - that carry out a specific task
  • functions - that perform a task and return a value.

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.

 
Parameters

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

Example : A subroutine that draws a rectangle, may use parameters such as height, width, border colour, border thickness, fill colour.

A Parameter may be passed...

  • by value
  • by reference

When a parameter is passed by value, a copy of the data is used in the subroutine, which is discarded when the subroutine is completed. The original data is unaffected by the running of the subroutine.

When a parameter is passed by reference, the address of the data is used by the subroutine. Any changes made to the data when the subroutine is executed are kept.