Programming: Subroutines (Procedures/Functions)
Programming: Subroutines (Procedures/Functions)
Subroutines in Programming
General Overview
- A subroutine (also known as procedure or function) in programming is a set of five instructions grouped together to perform a specific task.
- It promotes reusability and modular programming by enabling a program to be broken into manageable chunks.
- Subroutines make a program easier to understand, test, and debug.
Procedures and Functions
- A procedure is a type of subroutine which simply performs a task without returning any value.
- A function is a type of subroutine that performs a task and then returns a value.
- Both procedures and functions can be passed parameters or arguments, which are values or variables to be used within the subroutine.
Parameters and Arguments
- Parameters are variables defined in the subroutine declaration and serve as placeholders for values that will be passed into the subroutine.
- Arguments are the actual values that are passed into the subroutine when it is called.
- Parameters can be passed by value (the subroutine gets a copy of the value) or passed by reference (the subroutine gets access to the actual variable and can modify its value).
Return Statement
- The return statement is used in functions to send back an output value from the subroutine to the point in the program where the function was called.
- Once a return statement is executed, the program control goes back to the caller and no more instructions within the subroutine are processed.
Procedure and Function Call
- Subroutine call is an instruction that tells the program to move execution to the body of the subroutine.
- When the end of the subroutine is reached, execution returns to the point immediately following the original subroutine call.
- Functions can be integrated within expressions because they return a value, while procedures are generally treated as separate statement.
Scope and Lifetime of Variables
- Scope of a variable refers to the region of code within which a variable can be accessed.
- Local variables are declared within a subroutine and cannot be accessed outside of it.
- Global variables are accessible to any part of the program.
- The lifetime of a variable refers to the period during which the variable exists in memory while the program is running.
Remembering these key points should assist you in understanding the key aspects of subroutines in programming and their use in structuring program code.