Welcome to AE Resources
Converted document Converted document

FORTRAN 90+: FUNCTIONS

Functions allow one to write a calculation once and call it multiple times through out an overarching program. The basic format for a function is
!program using the function
CONTAINS
     type FUNCTION function_name(input_var1, ..., in_var_n)
        IMPLICIT NONE
        [declaration]
        [execution]
        [subprograms]
     END FUNCTION function_name
The function type defines the type of the output of the function. The rest of the above description is identical to that of PROGRAM and MODULE. A function can be written without input variables so that one can call the function in order to get a pre-ordained result based on parameters set in the MODULE or to get a single possibly complex answer to an algorithm to be in multiple places through out the whole program. The final output (result) is stored as the function_name in the execution part of the function.
The type of the input variables must be declared with an INTENT(IN) statement. The format for using INTENT(IN) is
type, INTENT(IN) :: input_var1, in_var2,...,in_var_n
This is contained in the declaration part of the function statement along with any other variables necessary for the function execution. These other variables are declaired the same way as any other PROGRAM or MODULE. INTENT(IN) variables can not be changed within the function. If one needs to make changes to the value it must be done through another variable assigned the value of the INTENT(IN) variable.
Similar to this is the INTENT(OUT) statement used with the declaration if the variable is generated within the subprogram and passed to the calling routine. INTENT(INOUT) lets an input variable be modified and output with a different value. It is not necessary to declare the INTENT of a variable, but it will create warning statements during compilation that may be constructive when coding.
Using user-defined functions is identical to using functions already defined by Fortran. The inputs must have a specific number of inputs depending on the function requirements; the type of the input must be correct according to the function requirements. The value created by the function is assigned to a variable that is the function’s name.