In this example we will compare the implementation of subroutines vs. functions.
program main
implicit none
real :: a,b, fn !Notice how the function has to be defined as real
a = 1.0
b = 1.0
print *, 'a befor subroutine: ', a
call sub(a)
print *, 'a after subroutine: ', a
print *, 'b befor function: ', b
print *, 'Result from function', fn(b), ', b after function: ', b
end program
As you may notice we run functions on a "traditional" maner, while subroutines require the command "call".
The implementation of the subroutine is pretty straight forward:
subroutine sub(a)
implicit none
real :: a
a = 2.0*a
end subroutine sub
function fn(b) result (c) !Defining c as a return variable
implicit none
real, intent(in) :: b !Many compilers require input variables to have intent(in)
real :: c
c = 2.0*b
end function fn
Intent(in) is telling the compiler that b is an un-changeable variable.
If your run this script you will get following output:
a befor subroutine: 1.0000000
a after subroutine: 2.0000000
b befor function: 1.0000000
Result from function 2.0000000 , b after function: 1.0000000
Press ENTER to continue--