Where Do My Functions Go?

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:

PROGRAM  program-name
IMPLICIT  NONE
[specification part]
[execution part]
CONTAINS
   [your functions]
END PROGRAM  program-name
In the above, following all executable statements, there is the keyword CONTAINS, followed by all of your functions, followed by END PROGRAM.

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.

Examples

A Important Note

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.

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
Please continue with the next important topic about scope rules.