Subroutines
Junrong Chen
Planet Cloud
A subroutine is a named block of code which performs a specific task within a program.
Pages
Modular programming When a program is short and simple, there is no need to break it up into subroutines. With a long, complex program, however, a top-down approach, in which the problem is broken down into a number of subtasks, is generally very helpful in designing the algorithm for a satisfactory solution
Programming with subroutines Using subroutines in a large program has many advantages:
A subroutine is small enough to be understood as a unit of code.
2021-03-15
1 min read
Variables used in the main program are by default global variables, and these can be used anywhere in the program, including within any subroutines. Within a subroutine, local variables can be used within the subroutine, and these exist only during the execution of the subroutine. They cannot be accessed outside the subroutine and changing them has no effect on any variable outside the subroutine, even if the variable happens to have the same name as the local variable.
2021-03-15
3 min read
Frequently, you need to pass values or variables to a subroutine. The exact form of the subroutine interface varies with the programming language, but will be similar to the examples below:
procedure subroutineName (parameter1, parameter2, ...) { // Do something return; } function subroutineName (parameter1, parameter2, ...) { // Do something return value; } In some programming languages, parameters may be passed in different ways. If a parameter is passed by value, its actual value is passed to the subroutine, where it is treated as a local variable.
2021-03-15
3 min read
A subroutine is a named block of code that performs a specific task within a program.
Most high-level languages support two types of subroutine, functions and procedures, which are called in a slightly different way. The procedures will not return a value and a function will return a value.
int function() { // Do something return 1; } void procedure() { // Do something return; }
2021-03-15
1 min read