Programming: Parameters of Subroutines
Programming: Parameters of Subroutines
Introduction to Parameters of Subroutines
-
A subroutine (also known as a method, procedure, function, or routine) is a set of instructions grouped together to perform a specific task within a program.
-
A parameter is a variable used by a subroutine to receive a piece of information that it needs to carry out its task.
-
Parameters are placed within the parentheses following the subroutine’s name, and multiple parameters are separated by commas.
Formal and Actual Parameters
-
Formal parameters are the parameter names and data types listed in the subroutine declaration.
-
Actual parameters (also called arguments) are the specific values or variables that the subroutine is called with in the actual code.
-
During a subroutine call, the actual parameters are matched with the formal parameters in order, from left to right.
Parameter Passing Methods
-
Pass-by-value: The parameter’s value is copied into the formal parameter of the subroutine. In this case, changes made within the subroutine don’t affect the original variable.
-
Pass-by-reference: Rather than providing a copy, a reference to the original variable is used. This means that any changes made within the subroutine will also change the original variable.
Default Parameters and Optional Parameters
-
A default parameter has a value assigned to it within the subroutine definition. This value is used if no value is provided when calling the subroutine.
-
Optional parameters are parameters that can be omitted when the subroutine is called.
-
Default and optional parameters allow more flexible subroutine calls and can help to simplify code.
Python Example
-
A function in Python might be defined with parameters like so:
def hello(name): print("Hello, " + name)
-
This function can then be called with an argument like so:
hello("World")
Understanding how to use parameters within subroutines is key to creating effective and reusable code. It forms a significant part of procedural programming, leveraging the strength of subroutines to prevent repetition and improve the structure of a program.