“Habit a second nature? Habit is ten times nature!” — The Duke of Wellington
The world would be a pretty tedious (and dangerous) place if we did not learn: if we had to figure out how to do the same things, day after day. Imagine having to figure out, again, tying shoes every morning. Imagine having to renew the knowledge not to touch hot burners every time we used a stove. The same principle holds true in programming: it is a benefit to store our knowledge of how to do something in such a way that it can be reused.
A subprogram is a computer program that can be used in other computer programs — incorporated by reference, so to speak. For example, in the first exercise in this section, we program a square root subroutine. In the second exercise in this section, we use a computation that requires square roots. By constructing a subprogram — a square root “black box” — we can reuse the knowledge of how to extract square roots in the second exercise.
Two types of subprograms are generally recognized. These are called functions and subroutines, and differ in whether they return a value. Generally, a function returns a value, and a subroutine does not. More importantly, functions are also generally regarded as being free of side effects — they do not change the program’s state other than by computing their result. Subroutines, lacking a return value, must change the program’s state — its variables or stored data — or its environment — the world surrounding the program — to have any effect at all.
A subprogram that always computed the square root of four would have markedly limited utility, certainly much more limited utility than a subprogram that computed the square root of any non-negative number. But with a subprogram that computes the square root of any non-negative number, there arises the question of how to communicate which square root is desired. This is done through a parameter. A parameter is a value that is passed to a subprogram to serve as the basis of its computations. Our example square root subprogram would need a variable to tell it the value for which the square root is desired.
(The terms “open” and “closed” are also used of subprograms that are coded in-line at what would be their calling site, or that are coded separately. This terminology is not further discussed here, but is used in other works.)
Copyright © 2001 Brian Hetrick
Page last updated 30 December 2001.
Building Blocks I
Control Flow II
A First Program
Data Structures I
Building Blocks II
Data Structures II