APortableFortran77Compiler S.I.Feldman P.J.Weinberger BellLaboratories MurrayHill,NewJersey07974 ABSTRACT TheFortranlanguagehasbeenrevised.Thenewlanguage,knownas Fortran77,becameanofficialAmericanNationalStandardonApril3,1978.We reporthereonacompilerandrun-timesystemforthenewextendedlanguage.It isbelievedtobethefirstcompleteFortran77systemtobeimplemented.This compilerisdesignedtobeportable,tobecorrectandcomplete,andtogenerate codecompatiblewithcallingsequencesproducedbyCcompilers.Inparticular, thisFortranisquiteusableonUNIX◯rsystems.Inthispaper,wedescribethe languagecompiled,interfacesbetweenprocedures,andfileformatsassumedby theI/Osystem.AppendixAdescribestheFortran77languageextensions. 1August1978 BerkeleyNotes ThisisastandardBellLaboratoriesdocumentreproducedwithminormodificationstothetext.TheBellLaboratory’sappendixon‘‘DifferencesBetweenFortran66andFortran77’’hasbeenchangedtoAppendixA,andalocalappendix hasbeenadded.AppendixBcontainsalistofFortran77references(somefrom theoriginalBelldocumentandsomeaddedatBerkeley). June1983 APortableFortran77Compiler S.I.Feldman P.J.Weinberger BellLaboratories MurrayHill,NewJersey07974 1.INTRODUCTION TheFortranlanguagehasbeenrevised.Thenewlanguage,knownasFortran77,becameanofficialAmericanNationalStandard[1]onApril3,1978.Fortran77supplants1966StandardFortran[2].Wereporthereonacompilerandrun-timesystemforthenewextendedlanguage.The compilerandcomputationlibrarywerewrittenbyS.I.F.,theI/OsystembyP.J.W.Webelieve ourstobethefirstcompleteFortran77systemtobeimplemented.Thiscompilerisdesignedto beportabletoanumberofdifferentmachines,tobecorrectandcomplete,andtogeneratecode compatiblewithcallingsequencesproducedbycompilersfortheClanguage[3].Inparticular,it isinuseonUNIXsystems.TwofamiliesofCcompilersareinuseatBellLaboratories,those basedonD.M.Ritchie’sPDP-11compiler[4]andthosebasedonS.C.Johnson’sportableCcom-piler[5].ThisFortrancompilercandrivethesecondpassesofeitherfamily.Inthispaper,we describethelanguagecompiled,interfacesbetweenprocedures,andfileformatsassumedbythe I/Osystem.Wewilldescribeimplementationdetailsincompanionpapers. 1.1.Usage Atpresent,versionsofthecompilerrunonandcompileforthePDP-11,theVAX-11/780,and theInterdata8/32UNIXsystems.Thecommandtorunthecompileris f77flagsfile... f77isageneral-purposecommandforcompilingandloadingFortranandFortran-related files.EFL[6]andRatfor[7]sourcefileswillbepreprocessedbeforebeingpresentedtothe Fortrancompiler.Candassemblersourcefileswillbecompiledbytheappropriateprograms.Objectfileswillbeloaded.(Thef77andcccommandscauseslightlydifferent loadingsequencestobegenerated,sinceFortranprogramsneedafewextralibrariesanda differentstartuproutinethandoCprograms.)Thefollowingfilenamesuffixesareunderstood: .fFortransourcefile .FFortransourcefile .eEFLsourcefile .rRatforsourcefile .cCsourcefile .sAssemblersourcefile .oObjectfile Argumentswhosenamesendwith.faretakentobeFortran77sourceprograms;theyare compiled,andeachobjectprogramisleftonthefileinthecurrentdirectorywhosenameis thatofthesourcewith.osubstitutedfor.f. Argumentswhosenamesendwith.FarealsotakentobeFortran77sourceprograms;these arefirstprocessedbytheCpreprocessorbeforebeingcompiledbyf77.

-2-Argumentswhosenamesendwith.ror.earetakentobeRatfororEFLsourceprograms, respectively;thesearefirsttransformedbytheappropriatepreprocessor,thencompiledby f77. Inthesameway,argumentswhosenamesendwith.cor.saretakentobeCorassembly sourceprogramsandarecompiledorassembled,producinga.ofile. Thefollowingflagsareunderstood: −cCompilebutdonotload.Outputforx.f,x.F,x.e,x.r,x.c,orx.sisput onfilex.o. −gHavethecompilerproduceadditionalsymboltableinformationfordbx(1). ThisonlyappliesontheVaxUNIXsystem.Donotusewith−O. −i2Onmachineswhichsupportshortintegers,makethedefaultintegerconstantsandvariablesshort(seesection2.14).(−i4isthestandardvalueof thisoption).Alllogicalquantitieswillbeshort. −mApplytheM4macropreprocessortoeachEFLorRatforsourcefilebefore usingtheappropriatecompiler. −ofilePutexecutablemoduleonfilefile.(Defaultisa.out). −onetripCompilecodethatperformseverydoloopatleastonce(seesection2.12). −pGeneratecodetoproduceusageprofiles. −pgGeneratecodeinthemannerof−p,butinvokearun-timerecordingmecha-nismthatkeepsmoreextensivestatistics. −wSuppressallwarningmessages. −w66SuppresswarningsaboutFortran66featuresused. −uMakethedefaulttypeofavariableundefined(seesection2.3). −CCompilecodethatchecksthatsubscriptsarewithinarraybounds. −Dname=def −DnameDefinethenametotheCpreprocessor,asifby‘#define’.Ifnodefinitionis given,thenameisdefinedas"1".(.Ffilesonly). −EstrUsethestringstrasanEFLoptioninprocessing.efiles. −FRatforandandEFLsourceprogramsarepre-processedintoFortranfiles, butthosefilesarenotcompiledorremoved. −Idir‘#include’fileswhosenamesdonotbeginwith‘/’arealwayssoughtfirstin thedirectoryofthefileargument,thenindirectoriesnamedin−Ioptions, thenindirectoriesonastandardlist.(.Ffilesonly). −OInvoketheobjectcodeoptimizer.Donotusewith−g. −RstrUsethestringstrasaRatforoptioninprocessing.rfiles. −UDonotconvertuppercaseletterstolowercase.Thedefaultistoconvert Fortranprogramstolowercaseexceptwithincharacterstringconstants. −SGenerateassembleroutputforeachsourcefile,butdonotassembleit. Assembleroutputforasourcefilex.f,x.F,x.e,x.r,orx.cisputonfile x.s. Otherflags,alllibrarynames(argumentsbeginning−l),andanynamesnotendingwithone oftheunderstoodsuffixesarepassedtotheloader. 1.2.DocumentationConventions Inrunningtext,wewriteFortrankeywordsandotherliteralstringsinboldfacelowercase. Exampleswillbepresentedinlightfacelowercase.Namesrepresentingaclassofvalueswill beprintedinitalics.

-3-1.3.ImplementationStrategy ThecompilerandlibraryarewrittenentirelyinC.ThecompilergeneratesCcompiler intermediatecode.SincethereareCcompilersrunningonavarietyofmachines,relatively smallchangeswillmakethisFortrancompilergeneratecodeforanyofthem.Furthermore, thisapproachguaranteesthattheresultingprogramsarecompatiblewithCusage.The runtimecomputationallibraryiscomplete.TheruntimeI/OlibrarymakesuseofD.M. Ritchie’sStandardCI/Opackage[8]fortransferringdata.Withthefewexceptions describedbelow,onlydocumentedcallsareused,soitshouldberelativelyeasytomodifyto runonotheroperatingsystems. 2.LANGUAGEEXTENSIONS Fortran77includesalmostallofFortran66asasubset.Wedescribethedifferencesbrieflyin AppendixA.Themostimportantadditionsareacharacterstringdatatype,file-oriented input/outputstatements,andrandomaccessI/O.Also,thelanguagehasbeencleanedupconsiderably. InadditiontoimplementingthelanguagespecifiedinthenewStandard,ourcompilerimplements afewextensionsdescribedinthissection.Mostareusefuladditionstothelanguage.The remainderareextensionstomakeiteasiertocommunicatewithCproceduresortopermitcompilationofold(1966Standard)programs. 2.1.DoubleComplexDataType Thenewtypedoublecomplexisdefined.Eachdatumisrepresentedbyapairofdouble precisionrealvariables.Adoublecomplexversionofeverycomplexbuilt-infunctionis provided.Thespecificfunctionnamesbeginwithzinsteadofc. 2.2.InternalFiles TheFortran77standardintroduces‘‘internalfiles’’(memoryarrays),butrestrictstheiruse toformattedsequentialI/Ostatements.OurI/Osystemalsopermitsinternalfilestobe usedinformatteddirectreadsandwrites. 2.3.ImplicitUndefinedStatement Fortran66hasafixedrulethatthetypeofavariablethatdoesnotappearinatypestatementisintegerifitsfirstletterisi,j,k,l,morn,andrealotherwise.Fortran77hasan implicitstatementforoverridingthisrule.Asanaidtogoodprogrammingpractice,we permitanadditionaltype,undefined.Thestatement implicitundefined(a-z) turnsofftheautomaticdatatypingmechanism,andthecompilerwillissueadiagnosticfor eachvariablethatisusedbutdoesnotappearinatypestatement.Specifyingthe−ucompilerflagisequivalenttobeginningeachprocedurewiththisstatement. 2.4.Recursion Proceduresmaycallthemselves,directlyorthroughachainofotherprocedures. 2.5.AutomaticStorage Twonewkeywordsarerecognized,staticandautomatic.Thesekeywordsmayappearas ‘‘types’’intypestatementsandinimplicitstatements.Localvariablesarestaticby default;thereisexactlyonecopyofthedatum,anditsvalueisretainedbetweencalls. Thereisonecopyofeachvariabledeclaredautomaticforeachinvocationoftheprocedure. Automaticvariablesmaynotappearinequivalence,data,orsavestatements.

-4-2.6.SourceInputFormat TheStandardexpectsinputtothecompilertobein72-columnformat:exceptincomment lines,thefirstfivecharactersarethestatementnumber,thenextisthecontinuationcharacter,andthenext66arethebodyoftheline.(Iftherearefewerthan72charactersona line,thecompilerpadsitwithblanks;charactersaftertheseventy-secondareignored.) InordertomakeiteasiertotypeFortranprograms,ourcompileralsoacceptsinputinvariablelengthlines.Anampersand‘‘&’’inthefirstpositionofalineindicatesacontinuation line;theremainingcharactersformthebodyoftheline.Atabcharacterinoneofthefirst sixpositionsofalinesignalstheendofthestatementnumberandcontinuationpartofthe line;theremainingcharactersformthebodyoftheline.Atabelsewhereonthelineis treatedasanotherkindofblankbythecompiler. IntheStandard,thereareonly26letters—Fortranisaone-caselanguage.Consistentwith ordinaryUNIXsystemusage,ourcompilerexpectslowercaseinput.Bydefault,thecompilerconvertsalluppercasecharacterstolowercaseexceptthoseinsidecharacterconstants. However,ifthe−Ucompilerflagisspecified,uppercaselettersarenottransformed.Inthis mode,itispossibletospecifyexternalnameswithuppercaselettersinthem,andtohave distinctvariablesdifferingonlyincase.Regardlessofthesettingoftheflag,keywordswill onlyberecognizedinlowercase. 2.7.IncludeStatement Thestatement include′stuff′ isreplacedbythecontentsofthefilestuff;includestatementsmaybenestedtoareasonabledepth,currentlyten. 2.8.BinaryInitializationConstants Avariablemaybeinitializedinadatastatementbyabinaryconstant,denotedbyaletter followedbyaquotedstring.Iftheletterisb,thestringisbinary,andonlyzeroesandones arepermitted.Iftheletteriso,thestringisoctal,withdigits0−7.Iftheletteriszorx, thestringishexadecimal,withdigits0−9,a−f.Thus,thestatements integera(3) dataa/b′1010′,o′12′,z′a′/ initializeallthreeelementsofatoten. 2.9.CharacterStrings ForcompatibilitywithCusage,thefollowingbackslashescapesarerecognized: \nnewline \ttab \bbackspace \fformfeed \0null \′apostrophe(doesnotterminateastring) \"quotationmark(doesnotterminateastring) \\\ \xx,wherexisanyothercharacter Fortran77onlyhasonequotingcharacter,theapostrophe.OurcompilerandI/Osystem recognizeboththeapostrophe‘‘′’’andthedouble-quote‘‘"’’.Ifastringbeginswithone varietyofquotemark,theothermaybeembeddedwithinitwithoutusingtherepeated quoteorbackslashescapes.

-5-Eachcharacterstringconstantappearingoutsideadatastatementisfollowedbyanull charactertoeasecommunicationwithCroutines. 2.10.Hollerith Fortran77doesnothavetheoldHollerith‘‘nh’’notation,thoughthenewStandardrecommendsimplementingtheoldHollerithfeatureinordertoimprovecompatibilitywithold programs.Inourcompiler,Hollerithdatamaybeusedinplaceofcharacterstringconstants,andmayalsobeusedtoinitializenon-charactervariablesindatastatements. 2.11.EquivalenceStatements Asaveryspecialandpeculiarcase,Fortran66permitsanelementofamultiplydimensionedarraytoberepresentedbyasingly-subscriptedreferenceinequivalencestate-ments.Fortran77doesnotpermitthisusage,sincesubscriptlowerboundsmaynowbedif-ferentfrom1.Ourcompilerpermitssinglesubscriptsinequivalencestatements,underthe interpretationthatallmissingsubscriptsareequalto1.Awarningmessageisprintedfor eachsuchincompletesubscript. 2.12.One-TripDOLoops TheFortran77Standardrequiresthattherangeofadoloopnotbeperformediftheinitial valueisalreadypastthelimitvalue,asin do10i=2,1 The1966Standardstatedthattheeffectofsuchastatementwasundefined,butitwascommonpracticethattherangeofadoloopwouldbeperformedatleastonce.Inorderto accommodateoldprograms,thoughtheywereinviolationofthe1966Standard,the −onetripcompilerflagcausesnon-standardloopstobegenerated. 2.13.CommasinFormattedInput TheI/OsystemattemptstobemorelenientthantheStandardwhenitseemsworthwhile. Whendoingaformattedreadofnon-charactervariables,commasmaybeusedasvaluesep-aratorsintheinputrecord,overridingthefieldlengthsgivenintheformatstatement.Thus, theformat (i10,f20.10,i4) willreadtherecord −345,.05e−3,12 correctly. 2.14.ShortIntegers Onmachinesthatsupporthalfwordintegers,thecompileracceptsdeclarationsoftypeinteger∗2.(OrdinaryintegersfollowtheFortranrulesaboutoccupyingthesamespaceasa REALvariable;theyareassumedtobeofCtypelongint;halfwordintegersareofCtype shortint.)Anexpressioninvolvingonlyobjectsoftypeinteger∗2isofthattype.Generic functionsreturnshortorlongintegersdependingontheactualtypesoftheirarguments.If aprocedureiscompiledusingthe−i2flag,allsmallintegerconstantswillbeoftypeinteger∗2.Iftheprecisionofaninteger-valuedintrinsicfunctionisnotdeterminedbythe genericfunctionrules,onewillbechosenthatreturnstheprevailinglength(integer∗2when the−i2commandflagisineffect).Whenthe−i2optionisineffect,allquantitiesoftype logicalwillbeshort.Notethattheseshortintegerandlogicalquantitiesdonotobeythe standardrulesforstorageassociation.

-6-2.15.AdditionalIntrinsicFunctions ThiscompilersupportsalloftheintrinsicfunctionsspecifiedintheFortran77Standard.In addition,therearefunctionsforperformingbitwiseBooleanoperations(or,and,xor,and not)andforaccessingtheUNIXcommandarguments(getargandiargc)andenvironment (getenv). 3.VIOLATIONSOFTHESTANDARD WeknowonlyafewwaysinwhichourFortransystemviolatesthenewstandard: 3.1.DoublePrecisionAlignment TheFortranStandards(both1966and1977)permitcommonorequivalencestatements toforceadoubleprecisionquantityontoanoddwordboundary,asinthefollowingexample: reala(4) doubleprecisionb,c equivalence(a(1),b),(a(4),c) Somemachines(e.g.,Honeywell6000,IBM360)requirethatdoubleprecisionquantitiesbe ondoublewordboundaries;othermachines(e.g.,IBM370),runinefficientlyifthisalignment ruleisnotobserved.Itispossibletotellwhichequivalencedandcommonvariablessuffer fromaforcedoddalignment,buteverydoubleprecisionargumentwouldhavetobe assumedonabadboundary.Toloadsuchaquantityonsomemachines,itwouldbenecessarytouseseparateoperationstomovetheupperandlowerhalvesintothehalvesofan alignedtemporary,thentoloadthatdoubleprecisiontemporary;thereversewouldbe neededtostorearesult.Wehavechosentorequirethatalldoubleprecisionrealandcomplexquantitiesfallonevenwordboundariesonmachineswithcorrespondinghardware requirements,andtoissueadiagnosticifthesourcecodedemandsaviolationoftherule. 3.2.DummyProcedureArguments Ifanyargumentofaprocedureisoftypecharacter,alldummyprocedureargumentsofthat proceduremustbedeclaredinanexternalstatement.Thisrequirementarisesasasubtle corollaryofthewaywerepresentcharacterstringargumentsandoftheone-passnatureof thecompiler.Awarningisprintedifadummyprocedureisnotdeclaredexternal.Codeis correctiftherearenocharacterarguments. 3.3.TandTLFormats Theimplementationofthet(absolutetab)andtl(leftwardtab)formatcodesisdefective. Thesecodesallowrereadingorrewritingpartoftherecordwhichhasalreadybeenprocessed(section6.3.2inAppendixA).Theimplementationusesseeks,soiftheunitisnot onewhichallowsseeks,suchasaterminal,theprogramisinerror.Abenefitoftheimplementationchosenisthatthereisnoupperlimitonthelengthofarecord,norisitnecessary topredeclareanyrecordlengthsexceptwherespecificallyrequiredbyFortranortheoperatingsystem. 3.4.CarriageControl TheStandardleavesasimplementationdependentwhichlogicalunit(s)aretreatedas ‘‘printer’’files.Inthisimplementationthereisnoprinterfileandthusnocarriagecontrolis recognizedonformattedoutput,exceptbyspecialarrangement[9]. 3.5.AssignedGoto Theoptionallistassociatedwithanassignedgotostatementisnotcheckedagainstthe actualassignedvalueduringexecution.

-7-4.INTER-PROCEDUREINTERFACE TobeabletowriteCproceduresthatcallorarecalledbyFortranprocedures,itisnecessaryto knowtheconventionsforprocedurenames,datarepresentation,returnvalues,andargumentlists thatthecompiledcodeobeys. 4.1.ProcedureNames OnUNIXsystems,thenameofacommonblockoraFortranprocedurehasanunderscore appendedtoitbythecompilertodistinguishitfromaCprocedureorexternalvariable withthesameuser-assignedname.Fortranlibraryprocedurenameshaveembeddedunder-scorestoavoidclasheswithuser-assignedsubroutinenames. 4.2.DataRepresentations ThefollowingisatableofcorrespondingFortranandCdeclarations: FortranC integer∗2xshortintx; integerxlongintx; logicalxlongintx; realxfloatx; doubleprecisionxdoublex; complexxstruct{floatr,i;}x; doublecomplexxstruct{doubledr,di;}x; character∗6xcharx[6]; (BytherulesofFortran,integer,logical,andrealdataoccupythesameamountofmemory.) 4.3.ReturnValues Afunctionoftypeinteger,logical,real,ordoubleprecisiondeclaredasaCfunction returnsthecorrespondingtype.Acomplexordoublecomplexfunctionisequivalentto aCroutinewithanadditionalinitialargumentthatpointstotheplacewherethereturn valueistobestored.Thus, complexfunctionf(...) isequivalentto f(temp,...) struct{floatr,i;}∗temp; ... Acharacter-valuedfunctionisequivalenttoaCroutinewithtwoextrainitialarguments:a dataaddressandalength.Thus, character∗15functiong(...) isequivalentto g(result,length,...) charresult[]; longintlength; ... andcouldbeinvokedinCby -8-charchars[15]; ... g(chars,15L,...); Subroutinesareinvokedasiftheywereinteger-valuedfunctionswhosevaluespecifieswhich alternatereturntouse.Alternatereturnarguments(statementlabels)arenotpassedtothe function,butareusedtodoanindexedbranchinthecallingprocedure.(Ifthesubroutine hasnoentrypointswithalternatereturnarguments,thereturnedvalueisundefined.)The statement callnret(∗1,∗2,∗3) istreatedexactlyasifitwerethecomputedgoto goto(1,2,3),nret() 4.4.ArgumentLists AllFortranargumentsarepassedbyaddress.Inaddition,foreveryargumentthatisof typecharacterorthatisadummyprocedure,anargumentgivingthelengthofthevalueis passed.(Thestringlengthsarelongintquantitiespassedbyvalue.)Theorderofargumentsisthen: Extraargumentsforcomplexandcharacterfunctions Addressforeachdatumorfunction Alongintforeachcharacterorprocedureargument Thus,thecallin externalf character∗7s integerb(3) ... callsam(f,b(2),s) isequivalenttothatin intf(); chars[7]; longintb[3]; ... sam(f,&b[1],s,0L,7L); NotethatthefirstelementofaCarrayalwayshassubscriptzero,butFortranarraysbegin at1bydefault.Fortranarraysarestoredincolumn-majororder,Carraysarestoredin row-majororder. 5.FILEFORMATS 5.1.StructureofFortranFiles Fortranrequiresfourkindsofexternalfiles:sequentialformattedandunformatted,and directformattedandunformatted.OnUNIXsystems,theseareallimplementedasordinary fileswhichareassumedtohavetheproperinternalstructure. FortranI/Oisbasedonrecords.WhenadirectfileisopenedinaFortranprogram,the recordlengthoftherecordsmustbegiven,andthisisusedbytheFortranI/Osystemto makethefilelookasifitismadeupofrecordsofthegivenlength.Inthespecialcasethat therecordlengthisgivenas1,thefilesarenotconsideredtobedividedintorecords,but aretreatedasbyte-addressablebytestrings;thatis,asordinaryUNIXfilesystemfiles.(A readorwriterequestonsuchafilekeepsconsumingbytesuntilsatisfied,ratherthanbeing -9-restrictedtoasinglerecord.) Thepeculiarrequirementsonsequentialunformattedfilesmakeitunlikelythattheywill everbereadorwrittenbyanymeansexceptFortranI/Ostatements.Eachrecordisprecededandfollowedbyanintegercontainingtherecord’slengthinbytes. TheFortranI/Osystembreakssequentialformattedfilesintorecordswhilereadingbyusing eachnewlineasarecordseparator.Theresultofreadingofftheendofarecordisundefined accordingtotheStandard.TheI/Osystemispermissiveandtreatstherecordasbeing extendedbyblanks.Onoutput,theI/Osystemwillwriteanewlineattheendofeach record.Itisalsopossibleforprogramstowritenewlinesforthemselves.Thisisanerror, buttheonlyeffectwillbethatthesinglerecordtheuserthoughthewrotewillbetreatedas morethanonerecordwhenbeingreadorbackspacedover. 5.2.PortabilityConsiderations TheFortranI/OsystemusesonlythefacilitiesofthestandardCI/Olibrary,awidelyavailableandfairlyportablepackage,withthefollowingtwononstandardfeatures:theI/OsystemneedstoknowwhetherafilecanbeusedfordirectI/O,andwhetherornotitispossibletobackspace.Bothofthesefacilitiesareimplementedusingthefseekroutine,sothere isaroutinecanseekwhichdeterminesiffseekwillhavethedesiredeffect.Also,the inquirestatementprovidestheuserwiththeabilitytofindoutiftwofilesarethesame, andtogetthenameofanalreadyopenedfileinaformwhichwouldenabletheprogramto reopenit.Thereforetherearetworoutineswhichdependonfacilitiesoftheoperatingsystemtoprovidethesetwoservices.Inanycase,theI/OsystemrunsonthePDP-11, VAX-11/780,andInterdata8/32UNIXsystems. 5.3.Pre-ConnectedFilesandFilePositions Units5,6,and0arepreconnectedwhentheprogramstarts.Unit5isconnectedtothe standardinput,unit6isconnectedtothestandardoutput,andunit0isconnectedtothe standarderrorunit.AllareconnectedforsequentialformattedI/O. Alltheotherunitsarealsopreconnectedwhenexecutionbegins.Unitnisconnectedtoa filenamedfort.n.Thesefilesneednotexist,norwilltheybecreatedunlesstheirunitsare usedwithoutfirstexecutinganopen.Thedefaultconnectionisforsequentialformatted I/O. TheStandarddoesnotspecifywhereafilewhichhasbeenexplicitlyopenedforsequential I/Oisinitiallypositioned.TheI/Osystemwillpositionthefileatthebeginning.Therefore awritewilldestroyanydataalreadyinthefile,butareadwillworkreasonably.Topositionafiletoitsend,usea‘read’loop,orthesystemdependent‘fseek’function.Thepreconnectedunits0,5,and6arepositionedastheycomefromtheprogram’sparentprocess.

-10-APPENDIXA:DifferencesBetweenFortran66andFortran77 Thefollowingisaverybriefdescriptionofthedifferencesbetweenthe1966[2]andthe1977[1] Standardlanguages.WeassumethatthereaderisfamiliarwithFortran66.Wedonotpretend tobecomplete,precise,orunbiased,butplantodescribewhatwefeelarethemostimportant aspectsofthenewlanguage.Thebestcurrentinformationonthe1977StandardisinpublicationsoftheX3J3SubcommitteeoftheAmericanNationalStandardsInstitute,andtheANSI X3.9-1978document,theofficialdescriptionofthelanguage.TheStandardiswritteninEnglish ratherthanameta-language,butitisforbiddingandlegalistic.Anumberoftutorialsandtext-booksareavailable(seeAppendixB). 1.FeaturesDeletedfromFortran66 1.1.Hollerith Allnotionsof‘‘Hollerith’’(nh)asdatahavebeenofficiallyremoved,althoughourcompiler, likealmostallintheforeseeablefuture,willcontinuetosupportthisarchaism. 1.2.ExtendedRange InFortran66,underasetofveryrestrictiveandrarely-understoodconditions,itispermissi-bletojumpoutoftherangeofadoloop,thenjumpbackintoit.Extendedrangehasbeen removedintheFortran77language.Therestrictionsaresospecial,andtheimplementation ofextendedrangeissounreliableinmanycompilers,thatthischangereallycountsasno loss. 2.ProgramForm 2.1.BlankLines Completelyblanklinesarenowlegalcommentlines. 2.2.ProgramandBlockDataStatements Amainprogrammaynowbeginwithastatementthatgivesthatprogramanexternal name: programwork Blockdataproceduresmayalsohavenames. blockdatastuff Thereisnowarulethatonlyoneunnamedblockdataproceduremayappearinaprogram. (Thisruleisnotenforcedbyoursystem.)TheStandarddoesnotspecifytheeffectofthe programandblockdatanames,buttheyareclearlyintendedtoaidconventionalloaders. 2.3.ENTRYStatement Multipleentrypointsarenowlegal.Subroutineandfunctionsubprogramsmayhaveadditionalentrypoints,declaredbyanentrystatementwithanoptionalargumentlist. entryextra(a,b,c) Executionbeginsatthefirststatementfollowingtheentryline.Allvariabledeclarations mustprecedeallexecutablestatementsintheprocedure.Iftheprocedurebeginswitha subroutinestatement,allentrypointsaresubroutinenames.Ifitbeginswithafunction statement,eachentryisafunctionentrypoint,withtypedeterminedbythetypedeclared fortheentryname.Ifanyentryisacharacter-valuedfunction,thenallentriesmustbe.In afunction,anentrynameofthesametypeasthatwherecontrolenteredmustbeassigneda value.Argumentsdonotretaintheirvaluesbetweencalls.(Theancienttrickofcallingone entrypointwithalargenumberofargumentstocausetheprocedureto‘‘remember’’the -11-locationsofthosearguments,theninvokinganentrywithjustafewargumentsforlatercal-culation,isstillillegal.Furthermore,thetrickdoesn’tworkinourimplementation,since argumentsarenotkeptinstaticstorage.) 2.4.DOLoops dovariablesandrangeparametersmaynowbeofinteger,real,ordoubleprecisiontypes. (Theuseoffloatingpointdovariablesisverydangerousbecauseofthepossibilityofunexpectedroundoff,andwestronglyrecommendagainsttheiruse.)Theactionofthedostatementisnowdefinedforallvaluesofthedoparameters.Thestatement do10i=l,u,d performsmax(0,⌊(u−l+d)/d⌋)iterations.Thedovariablehasapredictablevaluewhen exitingaloop:thevalueatthetimeagotoorreturnterminatestheloop;otherwisethe valuethatfailedthelimittest. 2.5.AlternateReturns Inasubroutineorsubroutineentrystatement,someoftheargumentsmaybenotedbyan asterisk,asin subroutines(a,∗,b,∗) Themeaningofthe‘‘alternatereturns’’isdescribedinsection5.2ofAppendixA. 3.Declarations 3.1.CHARACTERDataType Oneofthebiggestimprovementstothelanguageistheadditionofacharacter-stringdata type.Localandcommoncharactervariablesmusthavealengthdenotedbyaconstant expression: character∗17a,b(3,4) character∗(6+3)c Ifthelengthisomittedentirely,itisassumedequalto1.Acharacterstringargumentmay haveaconstantlength,orthelengthmaybedeclaredtobethesameasthatofthecorrespondingactualargumentatruntimebyastatementlike character∗(∗)a (Thereisanintrinsicfunctionlenthatreturnstheactuallengthofacharacterstring.) Characterarraysandcommonblockscontainingcharactervariablesmustbepacked:inan arrayofcharactervariables,thefirstcharacterofoneelementmustfollowthelastcharacter oftheprecedingelement,withoutholes. 3.2.IMPLICITStatement Thetraditionalimplieddeclarationrulesstillhold:avariablewhosenamebeginswithi,j, k,l,m,ornisoftypeinteger;othervariablesareoftypereal,unlessotherwisedeclared. Thisgeneralrulemaybeoverriddenwithanimplicitstatement: implicitreal(a-c,g),complex(w-z),character∗(17)(s) declaresthatvariableswhosenamebeginswithana,b,c,orgarereal,thosebeginning withw,x,y,orzareassumedcomplex,andsoon.Itisstillpoorpracticetodependon implicittyping,butthisstatementisanindustrystandard.

-12-3.3.PARAMETERStatement Itisnowpossibletogiveaconstantasymbolicname,asin parameter(x=17,y=x/3,pi=3.14159d0,s=′hello′) Thetypeofeachparameternameisgovernedbythesameimplicitandexplicitrulesasfora variable.Therightsideofeachequalsignmustbeaconstantexpression(anexpression madeupofconstants,operators,andalreadydefinedparameters). 3.4.ArrayDeclarations Arraysmaynowhaveasmanyassevendimensions.(Onlythreewerepermittedin1966.) Thelowerboundofeachdimensionmaybedeclaredtobeotherthan1byusingacolon. Furthermore,anadjustablearrayboundmaybeanintegerexpressioninvolvingconstants, arguments,andvariablesincommon. reala(−5:3,7,m:n),b(n+1:2∗n) Theupperboundonthelastdimensionofanarrayargumentmaybedenotedbyanasterisk toindicatethattheupperboundisnotspecified: integera(5,∗),b(∗),c(0:1,−2:∗) 3.5.SAVEStatement ApoorlyknownruleofFortran66isthatlocalvariablesinaproceduredonotnecessarily retaintheirvaluesbetweeninvocationsofthatprocedure.Atanyinstantintheexecutionof aprogram,ifacommonblockisdeclaredneitherinthecurrentlyexecutingprocedurenorin anyoftheproceduresinthechainofcallers,allofthevariablesinthatcommonblockalso becomeundefined.(Theonlyexceptionsarevariablesthathavebeendefinedinadata statementandneverchanged.)Theserulespermitoverlayandstackimplementationsfor theaffectedvariables.Fortran77permitsonetospecifythatcertainvariablesandcommon blocksaretoretaintheirvaluesbetweeninvocations.Thedeclaration savea,/b/,c leavesthevaluesofthevariablesaandcandallofthecontentsofcommonblockbunaffectedbyareturn.Thesimpledeclaration save hasthiseffectonallvariablesandcommonblocksintheprocedure.Acommonblockmust besavedineveryprocedureinwhichitisdeclaredifthedesiredeffectistooccur. 3.6.INTRINSICStatement AllofthefunctionsspecifiedintheStandardareinasinglecategory,‘‘intrinsicfunctions’’, ratherthanbeingdividedinto‘‘intrinsic’’and‘‘basicexternal’’functions.Ifanintrinsic functionistobepassedtoanotherprocedure,itmustbedeclaredintrinsic.Declaringit external(asinFortran66)causesafunctionotherthanthebuilt-inonetobepassed. 4.Expressions 4.1.CharacterConstants Characterstringconstantsaremarkedbystringssurroundedbyapostrophes.Ifanapostropheistobeincludedinaconstant,itisrepeated: ′abc′ ′ain′′t′ Therearenonull(zero-length)characterstringsinFortran77.Ourcompilerhastwo -13-differentquotationmarks,‘‘′’’and‘‘"’’.(Seesection2.9inthemaintext.) 4.2.Concatenation Onenewoperatorhasbeenadded,characterstringconcatenation,markedbyadoubleslash ‘‘//’’.Theresultofaconcatenationisthestringcontainingthecharactersoftheleft operandfollowedbythecharactersoftherightoperand.Thestrings ′ab′//′cd′ ′abcd′ areequal.Thestringsbeingconcatenatedmustbeofconstantlengthinallconcatenations thatarenottherightsidesofassignments.(Theonlyconcatenationexpressionsinwhicha characterstringdeclaredadjustablewitha‘‘∗(∗)’’modifierorasubstringdenotationwith nonconstantpositionvaluesmayappeararetherightsidesofassignments.) 4.3.CharacterStringAssignment Theleftandrightsidesofacharacterassignmentmaynotsharestorage.(Theassumed implementationofcharacterassignmentistocopycharactersfromtherighttotheleftside.) Iftheleftsideislongerthantheright,itispaddedwithblanks.Iftheleftsideisshorter thantheright,trailingcharactersarediscarded. 4.4.Substrings Itispossibletoextractasubstringofacharactervariableorcharacterarrayelement,using thecolonnotation: a(i,j)(m:n) isthestringof(n−m+1)charactersbeginningatthemthcharacterofthecharacterarray elementaij.Resultsareundefinedunlessm≤n.Substringsmaybeusedontheleftsides ofassignmentsandasprocedureactualarguments. 4.5.Exponentiation Itisnowpermissibletoraiserealquantitiestocomplexpowers,orcomplexquantitiestoreal orcomplexpowers.(Theprincipalpartofthelogarithmisused.)Also,multipleexponentiationisnowdefined: a∗∗b∗∗cisequivalenttoa∗∗(b∗∗c) 4.6.RelaxationofRestrictions Mixedmodeexpressionsarenowpermitted.(Forinstance,itispermissibletocombineintegerandcomplexquantitiesinanexpression.) Constantexpressionsarepermittedwhereaconstantisallowed,exceptindatastatements. (AconstantexpressionismadeupofexplicitconstantsandparametersandtheFortran operators,exceptforexponentiationtoafloating-pointpower.)Anadjustabledimension maynowbeanintegerexpressioninvolvingconstants,arguments,andvariablesinBcommon. Subscriptsmaynowbegeneralintegerexpressions;theoldcv±c′ruleshavebeenremoved. doloopboundsmaybegeneralinteger,real,ordoubleprecisionexpressions.Computed gotoexpressionsandI/Ounitnumbersmaybegeneralintegerexpressions. 5.ExecutableStatements -14-5.1.IF-THEN-ELSE Atlast,theif-then-elsebranchingstructurehasbeenaddedtoFortran.Itiscalleda‘‘Block If’’.ABlockIfbeginswithastatementoftheform if(...)then andendswithan endif statement.TwoothernewstatementsmayappearinaBlockIf.Theremaybeseveral elseif(...)then statements,followedbyatmostone else statement.IfthelogicalexpressionintheBlockIfstatementistrue,thestatementsfollowingituptothenextelseif,else,orendifareexecuted.Otherwise,thenextelseifstatementinthegroupisexecuted.Ifnoneoftheelseifconditionsaretrue,controlpassesto thestatementsfollowingtheelsestatement,ifany.(Theelseblockmustfollowallelseif blocksinaBlockIf.Ofcourse,theremaybeBlockIfsembeddedinsideofotherBlockIf structures.)Acaseconstructmayberendered: if(s.eq.′ab′)then ... elseif(s.eq.′cd′)then ... else ... endif 5.2.AlternateReturns Someoftheargumentsofasubroutinecallmaybestatementlabelsprecededbyanasterisk, asin: calljoe(j,∗10,m,∗2) Areturnstatementmayhaveanintegerexpression,suchas: returnk Iftheentrypointhasnalternatereturn(asterisk)argumentsandif1≤k≤n,thereturnis followedbyabranchtothecorrespondingstatementlabel;otherwisetheusualreturntothe statementfollowingthecallisexecuted. 6.Input/Output 6.1.FormatVariables Aformatmaybethevalueofacharacterexpression(constantorotherwise),orbestoredin acharacterarray,asin: write(6,′(i5)′)x 6.2.END=,ERR=,andIOSTAT=Clauses Areadorwritestatementmaycontainend=,err=,andiostat=clauses,asin:

-15-write(6,101,err=20,iostat=a(4)) read(5,101,err=20,end=30,iostat=x) Here5and6aretheunitsonwhichtheI/Oisdone,101isthestatementnumberofthe associatedformat,20and30arestatementnumbers,andaandxareintegers.Ifanerror occursduringI/O,controlreturnstotheprogramatstatement20.Iftheendofthefileis reached,controlreturnstotheprogramatstatement30.Inanycase,thevariablereferred tointheiostat=clauseisgivenavaluewhentheI/Ostatementfinishes.(Yes,thevalueis assignedtothenameontherightsideoftheequalsign.)Thisvalueiszeroifallwentwell, negativeforendoffile,andsomepositivevalueforerrors. 6.3.FormattedI/O 6.3.1.CharacterConstants Characterconstantsinformatsarecopiedliterallytotheoutput.Itisnotallowedtoread intocharacterconstantsorhollerithfields. Aformatmaybespecifiedasacharacterconstantwithinthereadorwritestatement. write(6,′(i2,′′isn′′′′t′′,i1)′)7,4 produces 7isn′t4 Intheexampleabove,theformatisthecharacterconstant (i2,′isn′′t′,i1) andtheimbeddedcharacterconstant isn′t iscopiedintotheoutput. Theexamplecouldhavebeenwrittenmorelegiblybytakingadvantageofthetwotypesof quotemarks. write(6,′(i2,"isn′′t",i1)′)7,4 However,thedoublequoteisnotstandardFortran77. 6.3.2.PositionalEditingCodes t,tl,tr,andxcodescontrolwherethenextcharacterisintherecord.trnornxspecifies thatthenextcharacterisntotherightofthecurrentposition.tlnspecifiesthatthenext characterisntotheleftofthecurrentposition,allowingpartsoftherecordtobereconsidered.tnsaysthatthenextcharacteristobecharacternumbernintherecord.(Seesection3.3inthemaintext.) 6.3.3.Colon AcolonintheformatterminatestheI/Ooperationiftherearenomoredataitemsinthe I/Olist,otherwiseithasnoeffect.Inthefragment x=′("hello",:,"there",i4)′ write(6,x)12 write(6,x) thefirstwritestatementprints hellothere12 whilethesecondonlyprints -16-hello 6.3.4.OptionalPlusSigns AccordingtotheStandard,eachimplementationhastheoptionofputtingplussignsin frontofnon-negativenumericoutput.Thespformatcodemaybeusedtomakethe optionalplussignsactuallyappearforallsubsequentitemswhiletheformatisactive.The ssformatcodeguaranteesthattheI/Osystemwillnotinserttheoptionalplussigns,and thesformatcoderestoresthedefaultbehavioroftheI/Osystem.(Sinceweneverputout optionalplussigns,ssandscodeshavethesameeffectinourimplementation.) 6.3.5.BlanksonInput Blanksinnumericinputfields,otherthanleadingblanks,willbeignoredfollowingabn codeinaformatstatement,andwillbetreatedaszerosfollowingabzcodeinaformat statement.Thedefaultforaunitmaybechangedbyusingtheopenstatement.(Blanks areignoredbydefault.) 6.3.6.UnrepresentableValues TheStandardrequiresthatifanumericitemcannotberepresentedintheformrequiredby aformatcode,theoutputfieldmustbefilledwithasterisks.(Wethinkthisshouldhave beenanoption.) 6.3.7.Iw.m Thereisanewintegeroutputcode,iw.m.Itisthesameasiw,exceptthattherewillbeat leastmdigitsintheoutputfield,including,ifnecessary,leadingzeros.Thecaseiw.0is special,inthatifthevaluebeingprintedis0,theoutputfieldisentirelyblank.iw.1isthe sameasiw. 6.3.8.FloatingPoint Oninput,exponentsmaystartwiththeletterE,D,e,ord.Allhavethesamemeaning. Onoutputwealwaysuseeord.Theeanddformatcodesalsohaveidenticalmeanings. Aleadingzerobeforethedecimalpointineoutputwithoutascalefactorisoptionalwith theimplementation.Thereisagw.dformatcodewhichisthesameasew.dandfw.don input,butwhichchoosesforeformatsforoutputdependingonthesizeofthenumberand ofd. 6.3.9.‘‘A’’FormatCode Theacodeisusedforcharacterdata.awusesafieldwidthofw,whileaplainausesthe lengthoftheinternalcharacteritem. 6.4.StandardUnits Therearedefaultformattedinputandoutputunits.Thestatement read10,a,b readsfromthestandardunitusingformatstatement10.Thedefaultunitmaybeexplicitly specifiedbyanasterisk,asin read(∗,10)a,b Similarly,thestandardoutputunitisspecifiedbyaprintstatementoranasteriskunit: print10 write(∗,10)

-17-6.5.List-DirectedFormatting List-directedI/OisakindoffreeforminputforsequentialI/O.Itisinvokedbyusingan asteriskastheformatidentifier,asin read(6,∗)a,b,c Oninput,valuesareseparatedbystringsofblanksandpossiblyacomma.Values,except forcharacterstrings,cannotcontainblanks.Endofrecordcountsasablank,exceptin characterstrings,whereitisignored.Complexconstantsaregivenastworealconstants separatedbyacommaandenclosedinparentheses.Anullinputfield,suchasbetweentwo consecutivecommas,meansthecorrespondingvariableintheI/Olistisnotchanged.Valuesmaybeprecededbyrepetitioncounts,asin 4∗(3.,2.)2∗,4∗′hello′ whichstandsfor4complexconstants,2nullvalues,and4stringconstants. Foroutput,suitableformatsarechosenforeachitem.Thevaluesofcharacterstringsare printed;theyarenotenclosedinquotes,sotheycannotbereadbackusinglist-directed input. 6.6.DirectI/O Afileconnectedfordirectaccessconsistsofasetofequal-sizedrecordseachofwhichis uniquelyidentifiedbyapositiveinteger.Therecordsmaybewrittenorreadinanyorder, usingdirectaccessI/Ostatements. Directaccessreadandwritestatementshaveanextraargument,rec=,whichgivesthe recordnumbertobereadorwritten. read(2,rec=13,err=20)(a(i),i=1,203) readsthethirteenthrecordintothearraya. Thesizeoftherecordsmustbegivenbyanopenstatement(seebelow).Directaccessfiles maybeconnectedforeitherformattedorunformattedI/O. 6.7.InternalFiles Internalfilesarecharacterstringobjects,suchasvariablesorsubstrings,orarraysoftype character.Intheformercasesthereisonlyasinglerecordinthefile;inthelattercaseeach arrayelementisarecord.TheStandardincludesonlysequentialformattedI/Ooninternal files.(I/Oisnotaveryprecisetermtousehere,butinternalfilesaredealtwithusingread andwrite.)Thereisnolist-directedI/Ooninternalfiles.Internalfilesareusedbygiving thenameofthecharacterobjectinplaceoftheunitnumber,asin character∗80x read(5,′(a)′)x read(x,′(i3,i4)′)n1,n2 whichreadsacharacterstringintoxandthenreadstwointegersfromthefrontofit.A sequentialreadorwritealwaysstartsatthebeginningofaninternalfile. Wealsosupportacompatibleextension,directI/Ooninternalfiles.ThisislikedirectI/O onexternalfiles,exceptthatthenumberofrecordsinthefilecannotbechanged.Inthis casearecordisasingleelementofanarrayofcharacterstrings. 6.8.OPEN,CLOSE,andINQUIREStatements Thesestatementsareusedtoconnectanddisconnectunitsandfiles,andtogatherinformationaboutunitsandfiles.

-18-6.8.1.OPEN Theopenstatementisusedtoconnectafilewithaunit,ortoaltersomepropertiesofthe connection.Thefollowingisaminimalexample. open(1,file=′fort.junk′) opentakesavarietyofargumentswithmeaningsdescribedbelow. unit=asmallnon-negativeintegerwhichistheunittowhichthefileistobecon-nected.Weallow,atthetimeofthiswriting,0through19.Ifthisparameteris thefirstoneintheopenstatement,theunit=canbeomitted. iostat=isthesameasinreadorwrite. err=isthesameasinreadorwrite. file=acharacterexpression,whichwhenstrippedoftrailingblanks,isthenameof thefiletobeconnectedtotheunit.Thefilenameshouldnotbegivenifthestatus=′scratch′. status=oneof′old′,′new′,′scratch′,or′unknown′.Ifthisparameterisnotgiven, ′unknown′isassumed.Themeaningof′unknown′isprocessordependent;our systemwillcreatethefileifitdoesn’texist.If′scratch′isgiven,atemporary filewillbecreated.Temporaryfilesaredestroyedattheendofexecution.If ′new′isgiven,thefilemustnotexist.Itwillbecreatedforbothreadingand writing.If′old′isgiven,itisanerrorforthefilenottoexist. access=′sequential′or′direct′,dependingonwhetherthefileistobeopenedfor sequentialordirectI/O. form=′formatted′or′unformatted′.OnUNIXsystemsform=′print′implies′formatted′withverticalformatcontrol. recl=apositiveintegerspecifyingtherecordlengthofthedirectaccessfilebeing opened.Wemeasureallrecordlengthsinbytes.OnUNIXsystemsarecord lengthof1hasthespecialmeaningexplainedinsection5.1ofthetext. blank=′null′or′zero′.ThisparameterhasmeaningonlyforformattedI/O.The defaultvalueis′null′.′zero′meansthatblanks,otherthanleadingblanks,in numericinputfieldsaretobetreatedaszeros. Openinganewfileonaunitwhichisalreadyconnectedhastheeffectoffirstclosingtheold file. 6.8.2.CLOSE closeseverstheconnectionbetweenaunitandafile.Theunitnumbermustbegiven.The optionalparametersareiostat=anderr=withtheirusualmeanings,andstatus=either ′keep′or′delete′.Forscratchfilesthedefaultis′delete′;otherwise′keep′isthedefault. ′delete′meansthefilewillberemoved.Asimpleexampleis close(3,err=17) 6.8.3.INQUIRE Theinquirestatementgivesinformationaboutaunit(‘‘inquirebyunit’’)orafile(‘‘inquire byfile’’).Simpleexamplesare: inquire(unit=3,namexx) inquire(file=′junk′,number=n,exist=l)

-19-file=acharactervariablespecifiesthefiletheinquireisabout.Trailingblanksin thefilenameareignored. unit=anintegervariablespecifiestheunittheinquireisabout.Exactlyoneof file=orunit=mustbeused. iostat=,err=areasbefore. exist=alogicalvariable.Thelogicalvariableissetto.true.ifthefileorunitexists andissetto.false.otherwise. opened=alogicalvariable.Thelogicalvariableissetto.true.ifthefileisconnectedtoaunitoriftheunitisconnectedtoafile,anditissetto.false.otherwise. number=anintegervariabletowhichisassignedthenumberoftheunitconnected tothefile,ifany. named=alogicalvariabletowhichisassigned.true.ifthefilehasaname,or .false.otherwise. name=acharactervariabletowhichisassignedthenameofthefile(inquirebyfile) orthenameofthefileconnectedtotheunit(inquirebyunit).Thenamewillbe thefullnameofthefile. access=acharactervariabletowhichwillbeassignedthevalue′sequential′ifthe connectionisforsequentialI/O,′direct′iftheconnectionisfordirectI/O.The valuebecomesundefinedifthereisnoconnection. sequential=acharactervariabletowhichisassignedthevalue′yes′ifthefilecould beconnectedforsequentialI/O,′no′ifthefilecouldnotbeconnectedforsequentialI/O,and′unknown′ifwecan’ttell. direct=acharactervariabletowhichisassignedthevalue′yes′ifthefilecouldbe connectedfordirectI/O,no′ifthefilecouldnotbeconnectedfordirectI/O,and ′unknown′ifwecan’ttell. form=acharactervariabletowhichisassignedthevalue′unformatted′ifthefileis connectedforunformattedI/O,′formatted′ifthefileisconnectedforformatted I/O,or′print′forformattedI/Owithverticalformatcontrol. formatted=acharactervariabletowhichisassignedthevalue′yes′ifthefilecould beconnectedforformattedI/O,′no′ifthefilecouldnotbeconnectedforformattedI/O,and′unknown′ifwecan’ttell. unformatted=acharactervariabletowhichisassignedthevalue′yes′ifthefile couldbeconnectedforunformattedI/O,′no′ifthefilecouldnotbeconnected forunformattedI/O,and′unknown′ifwecan’ttell. recl=anintegervariabletowhichisassignedtherecordlengthoftherecordsinthe fileifthefileisconnectedfordirectaccess. nextrec=anintegervariabletowhichisassignedonemorethanthenumberofthe thelastrecordreadfromafileconnectedfordirectaccess. blank=acharactervariabletowhichisassignedthevalue′null′ifnullblankcontrol isineffectforthefileconnectedforformattedI/O,′zero′ifblanksarebeingconvertedtozerosandthefileisconnectedforformattedI/O. ThegentlereaderwillrememberthatthepeoplewhowrotetheStandardprobablyweren’t thinkingofhisneeds.Hereisanexample.Thedeclarationsareomitted. open(1,file=′/dev/console′) OnaUNIXsystemthisstatementopenstheconsoleforformattedsequentialI/O.An inquirestatementforeitherunit1orfile"/dev/console"wouldrevealthatthefileexists,is connectedtounit1,hasaname,namely"/dev/console",isopenedforsequentialI/O,could -20-beconnectedforsequentialI/O,couldnotbeconnectedfordirectI/O(can’tseek),iscon-nectedforformattedI/O,couldbeconnectedforformattedI/O,couldnotbeconnectedfor unformattedI/O(can’tseek),hasneitherarecordlengthnoranextrecordnumber,andis ignoringblanksinnumericfields. IntheFORTRANenvironment,theonlywaytodiscoverwhatpermissionsyouhaveforafile istoopenitandtrytoreadandwriteit.Theerr=parameterwillreturnsystemerror numbers.Theinquirestatementdoesnotgiveawayofdeterminingpermissions. ForfurtherdiscussionoftheUNIXFortranI/Osystemsee‘‘Introductiontothef77I/O Library’’[9].

-21-APPENDIXB:ReferencesandBibliography References 1.AmericanNationalStandardProgrammingLanguageFORTRAN,ANSIX3.9-1978.NewYork: AmericanNationalStandardsInstitute,1978. 2.USAStandardFORTRAN,USASX3.9-1966.NewYork:UnitedStatesofAmericaStandards Institute,1966.ClarifiedinComm.ACM12:289(1969)andComm.ACM14:628(1971). 3.Kernighan,B.W.,andD.M.Ritchie.TheCProgrammingLanguage.EnglewoodCliffs: Prentice-Hall,1978. 4.Ritchie,D.M.Privatecommunication. 5.Johnson,S.C.‘‘APortableCompiler:TheoryandPractice,’’ProceedingsofFifthACMSymposiumonPrinciplesofProgrammingLanguages.1978. 6.Feldman,S.I.‘‘AnInformalDescriptionofEFL,’’internalmemorandum. 7.Kernighan,B.W.‘‘RATFOR—APreprocessorforRationalFortran,’’BellLaboratoriesComputingScienceTechnicalReport#55.1977. 8.Ritchie,D.M.Privatecommunication. 9.Wasley,D.L.‘‘Introductiontothef77I/OLibrary’’,UNIXProgrammer’sManual,Volume2c. Bibliography ThefollowingbooksordocumentsdescribeaspectsofFortran77.Thislistcannotpretendtobe complete.Certainlynoparticularendorsementisimplied. 1.Brainerd,WalterS.,etal.Fortran77Programming.HarperRow,1978. 2.Day,A.C.CompatibleFortran.CambridgeUniversityPress,1979. 3.Dock,V.Thomas.StructuredFortranIVProgramming.West,1979. 4.Feldman,S.I.‘‘TheProgrammingLanguageEFL,’’BellLaboratoriesTechnicalReport.June 1979. 5.Hume,J.N.,andR.C.Holt.ProgrammingFortran77.Reston,1979. 6.Katzan,Harry,Jr.Fortran77.VanNostrand-Reinhold,1978. 7.Meissner,LorenP.,andOrganick,ElliottI.Fortran77FeaturingStructuredProgramming, Addison-Wesley,1979. 8.Merchant,MichaelJ.ABC’sofFortranProgramming.Wadsworth,1979. 9.Page,Rex,andRichardDidday.Fortran77forHumans.West,1980. 10. Wagener,JerroldL.PrinciplesofFortran77Programming.Wiley,1980.

TableofContents 1.Introduction...........................1 1.1.Usage............................1 1.2.DocumentationConventions.....................2 1.3.ImplementationStrategy......................3 2.LanguageExtensions........................3 2.1.DoubleComplexDataType.....................3 2.2.InternalFiles..........................3 2.3.ImplicitUndefinedStatement....................3 2.4.Recursion...........................3 2.5.AutomaticStorage........................3 2.6.SourceInputFormat.......................4 2.7.IncludeStatement........................4 2.8.BinaryInitializationConstants....................4 2.9.CharacterStrings........................4 2.10.Hollerith...........................5 2.11.EquivalenceStatements......................5 2.12.One-TripDOLoops.......................5 2.13.CommasinFormattedInput....................5 2.14.ShortIntegers.........................5 2.15.AdditionalIntrinsicFunctions....................6 3.ViolationsoftheStandard......................6 3.1.DoublePrecisionAlignment.....................6 3.2.DummyProcedureArguments....................6 3.3.TandTLFormats........................6 3.4.CarriageControl.........................6 3.5.AssignedGoto.........................6 4.Inter-ProcedureInterface......................7 4.1.ProcedureNames........................7 4.2.DataRepresentations.......................7 4.3.ReturnValues..........................7 4.4.ArgumentLists.........................8 5.FileFormats...........................8 5.1.StructureofFortranFiles......................8 5.2.PortabilityConsiderations.....................9 5.3.Pre-ConnectedFilesandFilePositions.................9 AppendixA.DifferencesBetweenFortran66andFortran77...........10 1.FeaturesDeletedfromFortran66....................10 2.ProgramForm..........................10 3.Declarations...........................11 4.Expressions...........................12 5.ExecutableStatements.......................13 6.Input/Output..........................14 AppendixB.ReferencesandBibliography.................21