Fortran/Fortran procedures and functions

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Part of the Fortran WikiBook

Contents

[edit] Functions vs. Subroutines

Functions are simpler than subroutines. A function can only return one variable, and can be invoked from within a write statement, inside an if declaration if (function) then, etc. A subroutine handles many variables and can only be used as a stand-alone command.

[edit] Function

In Fortran one can use a function to return a value or an array of values. The following program calls a function to compute the sum of the square and the cube of an integer.

function func(i) result(j)
   integer, intent(in) :: i ! input
   integer             :: j ! output
   j = i**2 + i**3
end function func
  
program xfunc
   implicit none
   integer :: i,func
   i = 3
   print*,"sum of the square and cube of",i," is",func(i)
  end program xfunc

The intent(in) attribute of argument i means that i cannot be changed inside the function.


An alternative formulation (F77 compatible) is

FUNCTION func_name(a, b)
   INTEGER :: func_name
   INTEGER :: a
   REAL    :: b
   func_name = (2*a)+b
   RETURN
END FUNCTION
   
PROGRAM cows
   IMPLICIT NONE
   INTEGER :: func_name
   PRINT *,func_name(2, 1.3)
END PROGRAM

Notice that, in this case, the function needs to be declared many times (including in the program block (or wherever calls the function))


[edit] Subroutine

A subroutine can be used to return several values through its arguments. It is invoked with a call statement. Here is an example.

subroutine square_cube(i,isquare,icube)
  integer, intent(in)  :: i             ! input
  integer, intent(out) :: isquare,icube ! output
  isquare = i**2
  icube   = i**3
end subroutine square_cube

program xx
  implicit none
  integer :: i,isq,icub
  i = 4
  call square_cube(i,isq,icub)
  print*,"i,i^2,i^3=",i,isq,icub
end program xx

[edit] Intent

When declairing variables inside functions and subroutines that need to be passed in or out, intent must be added to the declaration.

intent(in) means that the variable value can enter, but not be changed

intent(out) means the variable is set inside the procedure and sent back to the main program with any initial values ignored.

intent(inout) means that the variable comes in with a value and leaves with a value.