What subroutines are
- A subroutine is a named block of code that carries out a specific task. It can be called (run) whenever it is needed.
- A procedure carries out a task. A function carries out a task and returns a value. (AQA calls both 'subroutines'; Edexcel calls them 'subprograms'.)
Parameters and return values
- Parameters are the variables in the subroutine's definition that receive data. The actual values passed in when it is called are called arguments.
- A function area(length, width) that returns length × width gives 12 when called as area(3, 4).
Local and global variables
- A local variable only exists inside its subroutine. A global variable can be used anywhere in the program.
- Local variables are good practice: the subroutine is self-contained, and its variable names can't clash with the rest of the program.
Why use subroutines?
- Code is written once and reused, so programs are shorter. Each subroutine can be tested separately, which makes debugging easier.
- Programs are easier to read and maintain, and different programmers can work on different subroutines at the same time.
- A structured approach uses subroutines with clear parameters and return values, and good documentation.
Key terms
- Subroutine
- A named block of code that carries out a specific task.
- Procedure
- A subroutine that carries out a task.
- Function
- A subroutine that returns a value.
- Parameter
- A variable in a subroutine's definition that receives a value.
- Argument
- The actual value passed into a subroutine when it is called.
- Return value
- The value a function sends back to where it was called.
- Local variable
- A variable that only exists inside its subroutine.
- Global variable
- A variable that can be used anywhere in the program.