You are on page 1of 3

3/23/2015

Fortran/FortranproceduresandfunctionsWikibooks,openbooksforanopenworld

Fortran/Fortranproceduresandfunctions
PartoftheFortranWikiBook

Contents
1FunctionsandSubroutines
2Function
3Subroutine
4Intent
5MoreonFunctionsvs.Subroutines

FunctionsandSubroutines
Inmostprograms,ablockofcodeisoftenreusedatseveralplaces.Inordertominimizeduplicating
codeandfacilitatemaintainingthecode,suchblocksofcodeshouldbeplacedwithinafunctionor
subroutine.AFortranfunctionissimilartoamathematicalfunction,whichtakesoneormany
parametersasinputsandreturnsasingleoutputvalue.AFortransubroutineisablockofcodethat
performssomeoperationontheinputvariables,andasaresultofcallingthesubroutine,theinput
variablesaremodified.
Anexpressioncontainingafunctioncall:

!func1isafunctiondefinedelsewhere
!ittakesanintegerasaninputandreturnsanotherintegerastheoutput
a=func1(b)

Acalltoasubroutine:

!sub1isasubroutinedefinedelsewhere
!sub1performssomeoperationoninputvariableseandf
callsub1(e,f)
!noweorf,orboth(orneither)maybemodified

Manyprogramminglanguagesdonotdistinguishbetweenfunctionsandsubroutines(e.g.C/C++,
Python,Java).Purefunctionalprogramminglanguages(e.g.Haskell)onlyallowsfunctions,because
subroutinesmodifyinputvariablesassideeffects,whichcancomplicatesthecodeinsomecases.In
Fortran,functionsandsubroutinesaredifferent:theformerreturnsavaluewhilethelatterdoesnot.
Functionsaresimplerthansubroutines.Afunctioncanonlyreturnonevariable,andcanbeinvoked
fromwithinexpressions,likeawritestatement,insideanifdeclarationif(function)then,etc.A
subroutinehandlesmanyvariablesandcanonlybeusedasastandalonecommand(usingthekeyword
call).
http://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions

1/3

3/23/2015

Fortran/FortranproceduresandfunctionsWikibooks,openbooksforanopenworld

Function
InFortran,onecanuseafunctiontoreturnavalueoranarrayofvalues.Thefollowingprogramcallsa
functiontocomputethesumofthesquareandthecubeofaninteger.

functionfunc(i)result(j)
integer,intent(in)::i!input
integer::j!output
j=i**2+i**3
endfunctionfunc

programxfunc
implicitnone
integer::i
integer::func
i=3
print*,"sumofthesquareandcubeof",i,"is",func(i)
endprogramxfunc

Theintent(in)attributeofargumentimeansthaticannotbechangedinsidethefunction.Notethatthe
returntypeoffuncneedstobedeclared.Ifthisisomitted,somecompilerswillnotcompile.Open64will
compiletheresultingcodewithwarning,butthebehaviourisilldefined.
Analternativeformulation(F77compatible)is

FUNCTIONfunc_name(a,b)
INTEGER::func_name
INTEGER::a
REAL::b
func_name=(2*a)+b
RETURN
ENDFUNCTION

PROGRAMcows
IMPLICITNONE
INTEGER::func_name
PRINT*,func_name(2,1.3)
ENDPROGRAM

Thereturntypeofthefunc_namestillneedstobedeclared,asabove.Theonlydifferenceishowthe
returntypeoffunc_nameisreferencedwithinfunc_name.Inthiscase,thereturnvariablehasthesame
nameasthefunctionitself.

Subroutine
Asubroutinecanbeusedtoreturnseveralvaluesthroughitsarguments.Itisinvokedwithacall
statement.Hereisanexample.

subroutinesquare_cube(i,isquare,icube)
integer,intent(in)::i!input
integer,intent(out)::isquare,icube!output
isquare=i**2
icube=i**3
endsubroutinesquare_cube

programxx
http://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions

2/3

3/23/2015

Fortran/FortranproceduresandfunctionsWikibooks,openbooksforanopenworld

implicitnone
integer::i,isq,icub
i=4
callsquare_cube(i,isq,icub)
print*,"i,i^2,i^3=",i,isq,icub
endprogramxx

Intent
Whendeclaringvariablesinsidefunctionsandsubroutinesthatneedtobepassedinorout,intentmaybe
addedtothedeclaration.
intent(in)meansthatthevariablevaluecanenter,butnotbechanged
intent(out)meansthevariableissetinsidetheprocedureandsentbacktothemainprogramwithany
initialvaluesignored.
intent(inout)meansthatthevariablecomesinwithavalueandleaveswithavalue(default).

MoreonFunctionsvs.Subroutines
Bothfunctionsandsubroutinescanmodifytheirinputvariables.Bynecessity,subroutinesmodifyinput
variables,sincetheydonotreturnanyoutputvalue.Functionsdonothaveto,butareallowed,by
default,tomodifyinputvariables.Afunctioncanbeturnedintoapurefunction,whichdoesnothave
anysideeffectsthroughtheuseoftheintentattributeonallinputvariables,andfurtherenforced
throughthekeywordpure.(Thepurekeywordimposesadditionalrestrictions,whichessentially
preventsthefunctionfromhavinganysideeffects.)
Anexampleofapurefunction.

purefunctionsquare(x)
real,intent(in)::x
real::square
square=x*x
endfunction

programmain
real::a,b,square
a=2.0
b=square(a)
!Afterinvokingthesquare(.)purefunction,wecanbesurethat
!besidesassigningtheoutputvalueofsquare(a)tob,
!nothingelsehasbeenchanged.
endprogrammain

Retrievedfrom"http://en.wikibooks.org/w/index.php?
title=Fortran/Fortran_procedures_and_functions&oldid=2770209"

Thispagewaslastmodifiedon24February2015,at18:13.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicense.additionalterms
mayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.

http://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions

3/3

You might also like