Now you have your functions. Where do they go? There are two places for you to add these functions in. They are either internal or external. This page only describes internal functions. See external subprogram for the details of using external functions.
Long time ago, we mentioned the structure of a Fortran program. From there, we know that the last part of a program is subprogram part. This is the place for us to put the functions. Here is the syntax:
In the above, following all executable statements, there is the keyword CONTAINS, followed by all of your functions, followed by END PROGRAM.PROGRAM program-name IMPLICIT NONE [specification part] [execution part] CONTAINS [your functions] END PROGRAM program-name
From now on, the program is usually referred to as the main program or the main program unit. A program always starts its execution with the first statement of the main program. When a function is required, the control of execution is transfered into the corresponding function until the function completes its task and returns a function values. Then, the main program continues its execution and uses the returned function value for further computation.
PROGRAM Avg IMPLICIT NONE REAL :: a, b, c, Mean READ(*,*) a, b, c Mean = Average(a, b, c) WRITE(*,*) a, b, c, Mean CONTAINS REAL FUNCTION Average(a, b, c) IMPLICIT NONE REAL, INTENT(IN) :: a, b, c Average = (a + b + c) / 3.0 END FUNCTION Average END PROGRAM Avg
PROGRAM TwoFunctions IMPLICIT NONE INTEGER :: a, b, BiggerOne REAL :: GeometricMean READ(*,*) a, b BiggerOne = Large(a,b) GeometricMean = GeoMean(a,b) WRITE(*,*) 'Input = ', a, b WRITE(*,*) 'Larger one = ', BiggerOne WRITE(*,*) 'Geometric Mean = ', GeometricMean CONTAINS INTEGER FUNCTION Large(a, b) IMPLICIT NONE INTEGER, INTENT(IN) :: a, b IF (a >= b) THEN Large = a ELSE Large = b END IF END FUNCTION Large REAL FUNCTION GeoMean(a, b) IMPLICIT NONE INTEGER, INTENT(IN) :: a, b GeoMean = SQRT(REAL(a*b)) END FUNCTION GeoMean END PROGRAM TwoFunctions
Although in general a function can "contain" other
functions, an internal function CANNOT contain any other functions. |
In the following example, the main program "contains" an internal function InternalFunction(), which in turn contains another internal function Funct(). This is incorrect, since an internal function cannot contain another internal function. In other words, the internal functions of a main program must be on the same level.
Please continue with the next important topic about scope rules.PROGRAM Wrong IMPLICIT NONE ......... CONTAINS INTEGER FUNCTION InternalFunction(.....) IMPLICIT NONE ........ CONTAINS REAL FUNCTION Funct(.....) IMPLICIT NONE ........ END FUNCTION Funct END FUNCTION InternalFunction END PROGRAM Wrong