Subroutines
Procedures and functions are types of subroutines. They are a sequence of instructions that perform a specific task or set of tasks
- Subroutines are often used to simplify a program by breaking it into smaller, more manageable parts. They can be used to:
- Avoid duplicating code and can be reused throughout a program,
- Improve the readability and maintainability of code,
- Perform calculations, to retrieve data, or to make decisions based on input.
- Parameters are values that are passed into a subroutine. They can:
- Be used to customise the behaviour of a subroutine,
- Be of different types,
- Have default values, which are used if no value is passed in,
- Be passed by value or by reference.
- When a parameter is passed by value, a copy of the parameter is made and used within the subroutine
- When a parameter is passed by reference, the original parameter is used within the subroutine, and any changes made to the parameter will be reflected outside of the subroutine
- Subroutines can have multiple parameters
What's the difference between a procedure and function?
Functions return a value whereas a procedure does not.
Defining and Calling a Subroutine
A subroutine only needs to be defined once to set it up. After this you can call it as many times as needed to use it.