Lately we have been studying how to divide programs into manageable ``chunks,'' or subprograms. So far, we have seen two kinds of chunks: main programs and functions. Subroutines are a third kind of chunk.
A function takes zero or more arguments and returns a result. A subroutine takes zero or more arguments and returns no result. That, in a nutshell, is the difference between functions and subroutines. If you're alert, however, you'll be wondering what possible purpose subroutines can serve, since they return no results. And that's a good question.
A function is called in order to obtain the value that it returns. On the other hand, a subroutine is called not for the value it returns (since it doesn't return one) but for the side effects that it causes while it is executing. You are now probably wondering what I mean by ``side effect.'' And that's another good question. To understand the idea of ``side effect,'' it is important to understand the difference between expressions and statements.
An expression is a piece of a Fortran program that has a value and thus can be used in contexts in which a value is needed. For example, the following are all expressions:
17 X+Y COS(0.0) SOLVE(A,B)
Notice that each of these expressions has a value. The value of the first expression is 17, the value of the second expression depends upon the values of X and Y, the value of the third expression is 1.0, and the value of the fourth expression depends upon the values of A and B. Notice that the last two expressions are function calls.
Expressions have the property that they can be used to build up more complicated expressions. For example, we can take each of the expressions above and use them to make new expressions:
17*2 (X+Y)+Z COS(0.0)/15.2 SOLVE(A,B) + SOLVE(B,A)
The purpose of this discussion of expressions has been to make the following point: in Fortran, function calls are expressions. They are used in contexts in which a value is needed, which makes sense since functions return values.
A statement is a piece of a Fortran program that carries out some action that has some side effect upon the computation. Roughly speaking, each line of a program is a statement (although some kinds statements that you will meet later often take up more than one line). For example, the following are all statements:
PRINT *, 'Hello'
X = 2*X + Y
CALL DISPLAY(A, B)
The first statement has the side effect of printing something out to the display; the second statement changes the value of X, and the third statement is a subroutine call. Presumably, the subroutine causes some side effects of its own. In Fortran, subroutine calls are statements, not expressions. Since they are not expressions, they cannot be called in contexts in which a value is needed, which makes sense since subroutines don't return values.
Hamlet Project