« previous | next» |
4.2 Subroutines
Subroutines are similar to, but more versatile than, external functions. Subroutines can be defined internally (following a CONTAINS statement) or externally (after the END PROGRAM statement). Functions are essentially simplified subroutines. The major differences between functions and subroutines are as follows:
SUBROUTINE name(dummy argument-list)
specification part
execution part
END SUBROUTINE
The formal argument-list is a list of identifiers for the input and output to the subroutine. These values are called dummy because they are used to pass information between the subroutine and the main program.
Subroutines are referenced in main programs using a CALL statement.
CALL name(actual argument-list)
The actual argument-list contains the variables, constants, or expressions that are to be used by the subroutine. The variables can be returned to the referencing program with values determined by the subroutine, or they can be used as input to the subroutine's execution. The arguments contained in the actual argument-list and the arguments contained in the dummy argument-list do not have to be the same; however, there does have to be the same number of arguments and their types must match.
Here is an example of a program calling a subroutine. The subroutine receives the name of a file, opens it, reads data, and returns that data to the referencing program.
MAIN PROGRAM
IMPLICIT NONE
CHARACTER(20) :: file_name
REAL :: vel, dens, conc
! Calling the subroutine.
! The arguments do not need
to be the same as
! the dummy arguments in the
subroutine.
! values for vel, dens, and conc will
be returned.
CALL Openfile(file_name, vel, dens, conc)
END PROGRAM
SUBROUTINE Openfile(name, a, b, c)
CHARACTER(20), INTENT(IN) :: name
REAL, INTENT (OUT) :: a, b, c
INTEGER :: OpenStatus
OPEN (UNIT = 10, FILE = name, ACTION
= "READ", &
IOSTAT = Openstatus)
IF (OpenStatus /= 0) STOP "error opening
file"
READ (10,*) a, b, c
END SUBROUTINE
« previous | next» |