Subroutines
A subroutine is a named block of code that carries out one task and can be called whenever it is needed. Breaking a program into subroutines makes it easier to read, test and reuse, and avoids repeating the same code.
Procedures and functions
Both are subroutines, but they differ in one key way:
- A procedure carries out a task but does not return a value. It is called on its own, e.g.
CALL DrawLine. - A function carries out a task and returns a single value to the point where it was called, so it is used inside an expression, e.g.
Area ← CalcArea(5, 4).
Key idea
The main difference: a function returns a value, a procedure does not. If a subroutine gives back a result to use, it is a function.
Parameters
A parameter is a value passed into a subroutine so it can work on different data each time. In CalcArea(5, 4), the values 5 and 4 are passed as parameters.
Remember
- A function returns a value; a procedure does not.
- Parameters pass data into a subroutine.
- Subroutines reduce repeated code and aid testing.