| Fortran 77 Language Reference |
Statements
This chapter describes the statements recognized by the Sun WorkShop FORTRAN 77 compiler,
f77. Nonstandard features are indicated by the symbol "". (See Chapter 1 for a discussion of the conforming standards). A table of sample statements appears in Appendix B.
ACCEPTThe
ACCEPTstatement reads from standard input and requires the following syntax:
ACCEPTgrname
Parameter Description f Format identifier iolist List of variables, substrings, arrays, and records grname Name of the namelist group
Description
ACCEPTf[,iolist]is equivalent toREADf[,iolist]and is for compatibility with older versions of FORTRAN. An example of list-directed input:
REAL VECTOR(10)ACCEPT *, NODE, VECTOR
ASSIGNThe
ASSIGNstatement assigns a statement label to a variable.
ASSIGNsTOi
Parameter Description s Statement label i Integer variable
Description
The label s is the label of an executable statement or a
FORMATstatement.The statement label must be the label of a statement that is defined in the same program unit as the
ASSIGNstatement.The integer variable i, once assigned a statement label, can be reassigned the same statement label, a different label, or an integer. It can not be declared
INTEGER*2.After assigning a statement label to a variable, you can reference it in:
- An assigned
GOTOstatement- An input/output statement, as a format identifier
Restrictions
The variable must be assigned a statement label before referencing it as a label in an assigned
GOTOstatement, or as a format identifier.While i is assigned a statement label value, do no arithmetic with i.
On 64-bit platforms, the actual value stored in variable i by the
ASSIGNstatement is not available to the program, except by the assignedGOTOstatement, or as a format identifier in an I/O statement. Also, only variables set by anASSIGNstatement can be used in an assignedGOTOor as a format identifier.Examples
Example 1: Assign the statement number of an executable statement:
IF(LB.EQ.0) ASSIGN 9 TO K...GO TO K...9 AKX = 0.0Example 2: Assign the statement number of a format statement:
INTEGER PHORMAT2 FORMAT ( A80 )ASSIGN 2 TO PHORMAT...WRITE ( *, PHORMAT ) 'Assigned a FORMAT statement no.'
AssignmentThe assignment statement assigns a value to a variable, substring, array element, record, or record field.
v
=e
Parameter Description v Variable, substring, array element, record, or record field e Expression giving the value to be assigned
Description
The value can be a constant or the result of an expression. The kinds of assignment statements: are arithmetic, logical, character, and record assignments.
Arithmetic Assignment
v is of numeric type and is the name of a variable, array element, or record field.
e is an arithmetic expression, a character constant, or a logical expression. Assigning logicals to numerics is nonstandard, and may not be portable; the resultant data type is, of course, the data type of v.
![]()
Execution of an arithmetic assignment statement causes the evaluation of the expression e, and conversion to the type of v (if types differ), and assignment of v with the resulting value typed according to the following table.
Note Compiling with any of the options-i2,-dbl,-r8, or-xtypemapcan alter the default data size of variables and expressions. This is discussed in Chapter 2. See also the Fortran User's Guide for a description of these options.
Example: An assignment statement:
REAL A, BDOUBLE PRECISION VV = A * BThe above code is compiled exactly as if it were the following:
REAL A, BDOUBLE PRECISION VV = DBLE( A * B )Logical Assignment
v is the name of a variable, array element, or record field of type logical.
e is a logical expression, or an integer between -128 and 127, or a single character constant.
Execution of a logical assignment statement causes evaluation of the logical expression e and assignment of the resulting value to v. If e is a logical expression (rather than an integer between -128 and 127, or a single character constant), then e must have a value of either true or false.
Logical expressions of any size can be assigned to logical variables of any size. The section on the
LOGICALstatement provides more details on the size of logical variables.Character Assignment
The constant can be a Hollerith constant or a string of characters delimited by apostrophes (') or quotes ("). The character string cannot include the control characters Control-A, Control-B, or Control-C; that is, you cannot hold down the Control key and press the A, B, or C keys. If you need those control characters, use the
char()function.If you use quotes to delimit a character constant, then you cannot compile with the
-xloption, because, in that case, a quote introduces an octal constant. The characters are transferred to the variables without any conversion of data, and may not be portable.Character expressions which include the
//operator can be assigned only to items of typeCHARACTER. Here, the v is the name of a variable, substring, array element, or record field of typeCHARACTER; e is a character expression.Execution of a character assignment statement causes evaluation of the character expression and assignment of the resulting value to v. If the length of e is more than that of v, characters on the right are truncated. If the length of e is less than that of v, blank characters are padded on the right.
Record Assignment
v and e are each a record or record field.
![]()
The e and v must have the same structure. They have the same structure if any of the following occur:
- Both e and v are fields with the same elementary data type.
- Both e and v are records with the same number of fields such that corresponding fields are the same elementary data type.
- Both e and v are records with the same number of fields such that corresponding fields are substructures with the same structure as defined
in 2, above.The sections on the
RECORDandSTRUCTUREstatements have more details on the structure of records.Examples
Example 1: Arithmetic assignment:
Example 2: Logical assignment:
LOGICAL B1*1, B2*1LOGICAL L3, L4L4 = .TRUE.B1 = L4B2 = B1Example 3: Hollerith assignment:
CHARACTER S*4INTEGER I2*2, I4*4REAL RS = 4HwxyzI2 = 2HyzI4 = 4HwxyzR = 4HwxyzExample 4: Character assignment:
CHARACTER BELL*1, C2*2, C3*3, C5*5, C6*6REAL ZC2 = 'z'C3 = 'uvwxyz'C5 = 'vwxyz'C5(1:2) = 'AB'C6 = C5 // C2BELL = CHAR(7) Control Character (^G)The results of the above are
:
C2C3C5C6receives 'z'a trailing blank receives'uvw' receives'ABxyz' receives'ABxyzz' an extrazleft over fromC5BELLreceives 07 hex Control-G, a bell Example 5: Record assignment and record field assignment:
AUTOMATICThe
AUTOMATICstatement makes each recursive invocation of the subprogram have its own copy of the specified items. It also makes the specified items become undefined outside the subprogram when the subprogram exits through a
RETURNstatement.
AUTOMATICvlist
Parameter Description vlist List of variables and arrays
Description
For automatic variables, there is one copy for each invocation of the procedure. To avoid local variables becoming undefined between invocations,
f77classifies every variable as either static or automatic with all local variables being static by default. For other than the default, you can declare variables as static or automatic in aSTATIC,
AUTOMATIC, or
IMPLICITstatement. See also the discussion of the-stackvaroption in the Fortran User's Guide.One usage of
AUTOMATICis to declare all automatic at the start of a function.Example: Recursive function with implicit automatic:
INTEGER FUNCTION NFCTRL( I )IMPLICIT AUTOMATIC (A-Z)...RETURNENDLocal variables and arrays are static by default, so in general, there is no need to use
SAVE. You should useSAVEto ensure portability. Also,SAVEis safer if you leave a subprogram by some way other than aRETURN.Restrictions
Automatic variables and arrays cannot appear in
DATAorSAVEstatements.Arguments and function values cannot appear in
DATA,RECORD,STATIC, orSAVEstatements becausef77always makes them automatic.Examples
Example: Some other uses of
AUTOMATIC:
AUTOMATIC A, B, CREAL P, D, QAUTOMATIC P, D, QIMPLICIT AUTOMATIC (X-Z)Example: Structures are unpredictable if
AUTOMATIC:
Restrictions
An
AUTOMATICstatement and a type statement cannot be combined to make anAUTOMATICtype statement. For example,AUTOMATIC REAL Xdoes not declare the variableXto be bothAUTOMATICandREAL; it declares the variableREALXto beAUTOMATIC.
BACKSPACEThe
BACKSPACEstatement positions the specified file to just before the preceding record.
BACKSPACE ([UNIT= ]u[, IOSTAT=ios] [, ERR=s])
Description
BACKSPACEin a terminal file has no effect.u must be connected for sequential access. Execution of a
BACKSPACEstatement on a direct-access file is not defined in the FORTRAN 77 Standard, and is unpredictable. We do not recommend using aBACKSPACEstatement on a direct-access file or an append access file.BACKSPACEon a file opened asFORM='BINARY'is not allowed and causes a runtime error.Execution of the
BACKSPACEstatement modifies the file position, as follows:
Prior to Execution After Execution Beginning of the file Remains unchanged Beyond the endfile record Before the endfile record Beginning of the previous record Start of the same record
Examples
Example 1: Simple backspace
:
BACKSPACE 2LUNIT = 2BACKSPACE LUNITExample 2: Backspace with error trap:
INTEGER CODEBACKSPACE ( 2, IOSTAT=CODE, ERR=9 )...9 WRITE (*,*) 'Error during BACKSPACE'STOP
BLOCK DATAThe
BLOCKDATAstatement identifies a subprogram that initializes variables and arrays in labeled common blocks.
BLOCK DATA [name]
Parameter Description name Symbolic name of the block data subprogram in which the BLOCKDATAstatement appears. This parameter is optional. It is a global name.
Description
A block data subprogram can contain as many labeled common blocks and data initializations as desired.
The
BLOCKDATAstatement must be the first statement in a block data subprogram.The only other statements that can appear in a block data subprogram are:
COMMONDATADIMENSIONENDEQUIVALENCEIMPLICITPARAMETERRECORDSAVESTRUCTURE- Type statements
Only an entity defined in a labeled common block can be initially defined in a block data subprogram.
If an entity in a labeled common block is initially defined, all entities having storage units in the common block storage sequence must be specified, even if they are not all initially defined.
Restrictions
Only one unnamed block data subprogram can appear in the executable program.
The same labeled common block cannot be specified in more than one block data subprogram in the same executable program.
The optional parameter name must not be the same as the name of an external procedure, main program, common block, or other block data subprogram in the same executable program. The name must not be the same as any local name in the subprogram.
Example
BLOCK DATA INITCOMMON /RANGE/ X0, X1DATA X0, X1 / 2.0, 6.0 /END
BYTEThe
BYTEstatement specifies the type to be 1-byte integer. It optionally specifies array dimensions and initializes with values.
BYTEv[/c/]...
Parameter Description v Name of a symbolic constant, variable, array, array declarator, function, or dummy function c List of constants for the immediately preceding name
Description
This is a synonym for
LOGICAL*1. ABYTEtype item can hold the logical values.TRUE.,.FALSE., one eight-bit data item, or an integer between -128 and 127.Example
BYTE BIT3 /8/, C1/'W'/, M/127/, SWITCH/.FALSE./
CALLThe
CALLstatement branches to the specified subroutine, executes the subroutine, and returns to the calling program after finishing the subroutine.
CALLsub[([ar[,ar]...])]
Parameter Description sub Name of the subroutine to be called ar Actual argument to be passed to the subroutine
Description
Arguments are separated by commas.
The FORTRAN 77 Standard requires that actual arguments in a
CALLstatement must agree in order, number, and type with the corresponding formal arguments of the referenced subroutine. The compiler checks this only when the-XlistEoption is on.Recursion is allowed. A subprogram can call itself directly, or indirectly by calling another subprogram that in turns calls this subroutine. Such recursion is nonstandard.
![]()
An actual argument, ar, must be one of the following:
- An expression
- An intrinsic function permitted to be passed as an argument; for a list of the intrinsics that cannot be actual arguments, see TABLE 4-2.
- An external function name
- A subroutine name
- An alternate return specifier,
*or&,followed by a statement number. The&is nonstandard.The simplest expressions, and most frequently used, include such constructs as:
- Constant
- Variable name
- Array name
- Formal argument, if the
CALLstatement is inside a subroutine- Record name
If a subroutine has no arguments, then a
CALLstatement that references that subroutine must not have any actual arguments. A pair of empty matching parentheses can follow the subroutine name.Execution of the
CALLstatement proceeds as follows:1. All expressions (arguments) are evaluated.2. All actual arguments are associated with the corresponding formal arguments, and the body of the subroutine is executed.3. Normally, the control is transferred back to the statement following theCALLstatement upon executing aRETURNstatement or anENDstatement in the subroutine. If an alternate return in the form ofRETURNn is executed, then control is transferred to the statement specified by the n alternate return specifier in theCALLstatement.
Note ACALLto a subprogram defined as aFUNCTIONrather than as aSUBROUTINEwill cause unexpected results and is not recommended. The compiler does not automatically detect such inappropriateCALLs and no warning is issued unless the-Xlistoption is specified.
Examples
Example 1: Character string:
CHARACTER *25 TEXTTEXT = 'Some kind of text string'CALL OOPS ( TEXT )ENDSUBROUTINE OOPS ( S )CHARACTER S*(*)WRITE (*,*) SENDExample 2: Alternate return:
Example 3: Another form of alternate return; the
&is nonstandard:
CALL RANK ( N, &8, &9 )![]()
Example 4: Array, array element, and variable:
REAL M(100,100), Q(2,2), YCALL SBRX ( M, Q(1,2), Y )...ENDSUBROUTINE SBRX ( A, D, E )REAL A(100,100), D, E...RETURNENDIn this example, the real array
Mmatches the real array,A, and the real array elementQ(1,2)matches the real variable,D.Example 5: A structured record and field; the record is nonstandard:
![]()
In the above example, the record
NEWmatches the recordCURRENT, and the integer variable,K, matches the record field,PRIOR.OLD.
CHARACTERThe
CHARACTERstatement specifies the type of a symbolic constant, variable, array, function, or dummy function to be character.Optionally, it initializes any of the items with values and specifies array dimensions.
CHARACTER [*len[,]]v[*len/c/]] ...
Description
Each character occupies 8 bits of storage, aligned on a character boundary. Character arrays and common blocks containing character variables are packed in an array of character variables. The first character of one element follows the last character of the preceding element, without holes.
The length, len must be greater than 0. If len is omitted, it is assumed equal to 1.
For local and common character variables, symbolic constants, dummy arguments, or function names, len can be an integer constant, or a parenthesized integer constant expression.
For dummy arguments or function names, len can have another form: a parenthesized asterisk, that is,
CHARACTER*(*), which denotes that the function name length is defined in referencing the program unit, and the dummy argument has the length of the actual argument.For symbolic constants, len can also be a parenthesized asterisk, which indicates that the name is defined as having the length of the constant. This is shown in Example 5 in the next section.
The list c of constants can be used only for a variable, array, or array declarator. There can be only one constant for the immediately preceding variable, and one constant for each element of the immediately preceding array.
Examples
Example 1: Character strings and arrays of character strings:
CHARACTER*17 A, B(3,4), V(9)CHARACTER*(6+3) CThe above code is exactly equivalent to the following:
CHARACTER A*17, B(3,4)*17, V(9)*17CHARACTER C*(6+3)Both of the above two examples are equivalent to the nonstandard variation:
![]()
CHARACTER A*17, B*17(3,4), V*17(9) nonstandardThere are no null (zero-length) character-string variables. A one-byte character string assigned a null constant has the length zero.
Example 2: No null character-string variables:
CHARACTER S*1S = ''During execution of the assignment statement, the variable
Sis precleared to blank, and then zero characters are moved intoS, soScontains one blank; because of the declaration, the intrinsic functionLEN(S)will return a length of1. You cannot declare a size of less than 1, so this is the smallest length string variable you can get.Example 3: Dummy argument character string with constant length:
SUBROUTINE SWAN( A )CHARACTER A*32Example 4: Dummy argument character string with length the same as corresponding actual argument:
SUBROUTINE SWAN( A )CHARACTER A*(*)...Example 5: Symbolic constant with parenthesized asterisk:
CHARACTER *(*) INODEPARAMETER (INODE = 'Warning: INODE corrupted!')The intrinsic function
LEN(INODE)returns the actual declared length of a character string. This is mainly for use withCHAR*(*)dummy arguments.Example 6: The
LENintrinsic function:
CHARACTER A*17A = "xyz"PRINT *, LEN( A )ENDThe above program displays
17, not3.
CLOSEThe
CLOSEstatement disconnects a file from a unit.
CLOSE([UNIT=]u[,STATUS= sta] [, IOSTAT= ios] [, ERR= s])
Description
The options can be specified in any order.
The
DISP=andDISPOSE=options are allowable alternates forSTATUS=, with a warning, if the-ansiflag is set.Execution of
CLOSEproceeds as follows:1. The specified unit is disconnected.2. If sta isDELETE, the file connected to the specified unit is deleted.3. If anIOSTATargument is specified, ios is set to zero if no error was encountered; otherwise, it is set to a positive value.Comments
All open files are closed with default sta at normal program termination. Regardless of the specified sta, scratch files, when closed, are always deleted.
Execution of a
CLOSEstatement specifying a unit that does not exist, or a unit that has no file connected to it, has no effect.Execution of a
CLOSEstatement specifying a unit zero (standard error) is not allowed, but you can reopen it to some other file.The unit or file disconnected by the execution of a
CLOSEstatement can be connected again to the same, or a different, file or unit.
Note For tape I/O, use theTOPEN()routines.
Examples
Example 1: Close and keep:
CLOSE ( 2, STATUS='KEEP')Example 2: Close and delete:
CLOSE ( 2, STATUS='DELETE', IOSTAT=I )Example 3: Close and keep a scratch file even though the status is
SCRATCH:
OPEN ( 2, STATUS='SCRATCH')...CLOSE ( 2, STATUS='KEEP', IOSTAT=I )
COMMONThe
COMMONstatement defines a block of main memory storage so that different program units can share the same data without using arguments.
COMMON [/[cb]/]nlist[[,]/[cb]/nlist] ...
Parameter Description cb Common block name nlist List of variable names, array names, and array declarators
Description
If the common block name is omitted, then blank common block is assumed.
Any common block name including blank common can appear more than once in
COMMONstatements in the same program unit. The list nlist following each successive appearance of the same common block name is treated as a continuation of the list for that common block name.The size of a common block is the sum of the sizes of all the entities in the common block, plus space for alignment.
Within a program, all common blocks in different program units that have the same name must be of the same size. However, blank common blocks within a program are not required to be of the same size.
Restrictions
Formal argument names and function names cannot appear in a
COMMONstatement.An
EQUIVALENCEstatement must not cause the storage sequences of two different common blocks in the same program unit to be associated. See Example 2.An
EQUIVALENCEstatement must not cause a common block to be extended on the left-hand side. See Example 4.Examples
Example 1:
Unlabeled common and labeled common:
DIMENSION V(100)COMMON V, MCOMMON /LIMITS/I, J...In the above example,
VandMare in the unlabeled common block;IandJare defined in the named common block,LIMITS.Example 2: You cannot associate storage of two different common blocks in the same program unit:
COMMON /X/ ACOMMON /Y/ BEQUIVALENCE ( A, B) Not allowedExample 3: An
EQUIVALENCEstatement can extend a common block on the right-hand side:
DIMENSION A(5)COMMON /X/ BEQUIVALENCE ( B, A)Example 4: An
EQUIVALENCEstatement must not cause a common block to be extended on the left-hand side:
COMMON /X/ AREAL B(2)EQUIVALENCE ( A, B(2)) Not allowed
COMPLEXThe
COMPLEXstatement specifies the type of a symbolic constant, variable, array, function, or dummy function to be complex, optionally specifies array dimensions and size, and initializes with values.
COMPLEX [*len[,]] v [*len[/c/]] [,v[*len[/c/]]...
Description
The declarations can be:
COMPLEX,COMPLEX*8,COMPLEX*16, orCOMPLEX*32. Specifying the size is nonstandard.![]()
COMPLEXFor a declaration such as
COMPLEX W, the variableWis usually twoREAL*4elements contiguous in memory, interpreted as a complex number.If you do not specify the size, a default size is used.
The default size for a declaration such as
COMPLEXWcan be altered by compiling with any of the options-dbl,-r8, or-xtypemap. See the discussion in Chapter 2 for details.
COMPLEX*8![]()
For a declaration such as
COMPLEX*8 W, the variableWis always twoREAL*4elements contiguous in memory, interpreted as a complex number.
COMPLEX*16![]()
For a declaration such as
COMPLEX*16 W,Wis always twoREAL*8elements contiguous in memory, interpreted as a double-width complex number.
COMPLEX*32![]()
(SPARC only) For a declaration such as
COMPLEX*32 W, the variableWis always twoREAL*16elements contiguous in memory, interpreted as a quadruple-width complex number.Comments
There is a double-complex version of each complex built-in function. Generally, the specific function names begin with
ZorCDinstead ofC, except for the two functionsDIMAGandDREAL, which return a real value.There are specific complex functions for quad precision (SPARC only). In general, where there is a specific
REALa correspondingCOMPLEXwith aCprefix, and a correspondingCOMPLEXDOUBLEwith aCDprefix, there is also a quad-precisionCOMPLEXfunction with aCQprefix. Examples are:SIN(),CSIN(),CDSIN(),CQSIN().Examples
Example 1: Complex variables. These statements are equivalent.
COMPLEX U, VCOMPLEX*8 U, VCOMPLEX U*8, V*8Example 2: Initialize complex variables:
COMPLEX U/(1, 9.0)/,V/(4.0, 5)/A complex constant is a pair of numbers, either integers or reals.
Example 3: Double complex, with initialization:
COMPLEX U*16 / (1.0D0, 9 ) /, V*16 / (4.0, 5.0D0) /COMPLEX*16 X / (1.0D0, 9.0) /, Y / (4.0D0, 5 ) /A double-complex constant is a pair of numbers, and at least one number of the pair must be double precision.
Example 4: Quadruple complex, with initialization (SPARC only):
COMPLEX U*32 / (1.0Q0, 9 ) /, V*32 / (4.0, 5.0Q0) /COMPLEX*32 X / (1.0Q0, 9.0) /, Y / (4.0Q0, 5 ) /A quadruple complex constant is a pair of numbers, and at least one number of the pair must be quadruple precision.
Example 5: Complex arrays, all of which are nonstandard (SPARC only):
COMPLEX R*16(5), S(5)*16COMPLEX U*32(5), V(5)*32COMPLEX X*8(5), Y(5)*8
CONTINUEThe
CONTINUEstatement is a "do-nothing" statement.
[label] CONTINUE
Parameter Description label Executable statement number
Description
The
CONTINUEstatement is often used as a place to hang a statement label, usually it is the end of aDOloop.The
CONTINUEstatement is used primarily as a convenient point for placing a statement label, particularly as the terminal statement in aDOloop. Execution of aCONTINUEstatement has no effect.If the
CONTINUEstatement is used as the terminal statement of aDOloop, the next statement executed depends on theDOloop exit condition.Example
DIMENSION U(100)S = 0.0DO 1 J = 1, 100S = S + U(J)IF ( S .GE. 1000000 ) GO TO 21 CONTINUESTOP2 CONTINUE. . .
DATAThe
DATAstatement initializes variables, substrings, arrays, and array elements.
DATAnlist/clist/[[,]nlist/clist/]...
Description
All initially defined items are defined with the specified values when an executable program begins running.
r*c is equivalent to r successive occurrences of the constant c.
A
DATAstatement is a nonexecutable statement, and must appear after all specification statements, but it can be interspersed with statement functions and executable statements, although this is non-standard.
Note Initializing a local variable in aDATAstatement after an executable reference to that variable is flagged as an error when compiling with the-stackvaroption. See the Sun WorkShop Fortran User's Guide.
Taking into account the repeat factor, the number of constants in clist must be equal to the number of items in the nlist. The appearance of an array in nlist is equivalent to specifying a list of all elements in that array. Array elements can be indexed by constant subscripts only.
Automatic variables or arrays cannot appear on a
DATAstatement.Normal type conversion takes place for each noncharacter member of the clist.
Character Constants in the
DATAStatementIf the length of a character item in nlist is greater than the length of the corresponding constant in clist, it is padded with blank characters on the right.
If the length of a character item in nlist is less than that of the corresponding constant in clist, the additional rightmost characters are ignored.
If the constant in clist is of integer type and the item of nlist is of character type, they must conform to the following rules:
- The character item must have a length of one character.
- The constant must be of type integer and have a value in the range 0 through 255. For
^A,^B,^C, do not hold down the Control key and press A, B, or C; use theCHARintrinsic function.If the constant of clist is a character constant or a Hollerith constant, and the item of nlist is of type
INTEGER, then the number of characters that can be assigned is 2 or 4 forINTEGER*2andINTEGER*4respectively. If the character constant or the Hollerith constant has fewer characters than the capacity of the item, the constant is extended on the right with spaces. If the character or the Hollerith constant contains more characters than can be stored, the constant is truncated on the right.Implied
DOListsAn nlist can specify an implied
DOlist for initialization of array elements.The form of an implied
DOlist is:(dlist, iv
=m1,m2[,m3])
The range of an implied
DOloop is dlist. The iteration count for the impliedDOis computed from m1, m2, and m3, and it must be positive.Implied
DOlists may also appear within the variables lists on I/O statementsREAD, andWRITE.Variables
Variables can also be initialized in type statements. This is an extension of the FORTRAN 77 Standard. Examples are given under each of the individual type statements and under the general type statement.
![]()
Examples
Example 1: Character, integer, and real scalars. Real arrays:
CHARACTER TTL*16REAL VEC(5), PAIR(2)DATA TTL /'Arbitrary Titles'/,& M /9/, N /0/,& PAIR(1) /9.0/,& VEC /3*9.0, 0.1, 0.9/...Example 2: Arrays--implied
DO:
REAL R(3,2), S(4,4)DATA ( S(I,I), I=1,4)/4*1.0/,& ( R(I,J), J=1,3), I=1,2)/6*1.0/...Example 3: Mixing an integer and a character:
CHARACTER CR*1INTEGER I*2, N*4DATA I /'00'/,N/4Hs12t/,CR/13/...
DECODE/ENCODE
ENCODEwrites to a character variable, array, or array element.![]()
DECODEreads from a character variable, array, or array element. Data is edited according to the format identifier.Similar functionality can be accomplished, using internal files with formatted sequential
WRITEstatements andREADstatements.ENCODEandDECODEare not in the FORTRAN 77 Standard, and are provided for compatibility with older versions of FORTRAN.
ENCODE (size,f,buf[,IOSTAT=ios] [,ERR=s]) [iolist]
DECODE (size,f,buf[,IOSTAT=ios] [,ERR=s]) [iolist]
Description
The entities in the I/O list can be: variables, substrings, arrays, array elements, record fields. A simple unsubscripted array name specifies all of the elements of the array in memory storage order, with the leftmost subscript increasing more rapidly.
Execution proceeds as follows:
- The
ENCODEstatement translates the list items to character form according to the format identifier, and stores the characters in buf. AWRITEoperation on internal files does the same.- The
DECODEstatement translates the character data in buf to internal (binary) form according to the format identifier, and stores the items in the list. AREADstatement does the same.- If buf is an array, its elements are processed in the order of subscript progression, with the leftmost subscript increasing more rapidly.
- The number of characters that an
ENCODEor aDECODEstatement can process depends on the data type of buf. For example, anINTEGER*2array can contain two characters per element, so that the maximum number of characters is twice the number of elements in that array. A character variable or character array element can contain characters equal in number to its length. A character array can contain characters equal in number to the length of each element multiplied by the number of elements.- The interaction between the format identifier and the I/O list is the same as for a formatted I/O statement.
Example
A program using
DECODE/ENCODE:
CHARACTER S*6 / '987654' /, T*6INTEGER V(3)*4DECODE( 6, '(3I2)', S ) VWRITE( *, '(3I3)') VENCODE( 6, '(3I2)', T ) V(3), V(2), V(1)PRINT *, TENDThe above program has this output:
98 76 54547698The
DECODEreads the characters ofSas 3 integers, and stores them intoV(1),V(2), andV(3).The
ENCODEstatement writes the valuesV(3),V(2), andV(1)intoTas characters;Tthen contains'547698'.
DIMENSIONThe
DIMENSIONstatement specifies the number of dimensions for an array, including the number of elements in each dimension.Optionally, the
DIMENSIONstatement initializes items with values.
DIMENSIONa(d) [,a(d)]...
Parameter Description a Name of an array d Specifies the dimensions of the array. It is a list of 1 to 7 declarators separated by commas.
Description
This section contains descriptions for the dimension declarator and the arrays.
Dimension Declarator
The lower and upper limits of each dimension are designated by a dimension declarator. The form of a dimension declarator is:
[dd1:]dd2dd1 and dd2 are dimension bound expressions specifying the lower- and upper- bound values. They can be arithmetic expressions of type integer or real. They can be formed using constants, symbolic constants, formal arguments, or variables defined in the
COMMONstatement. Array references and references to user-defined functions cannot be used in the dimension bound expression. dd2 can also be an asterisk. If dd1 is not specified, a value of one is assumed. The value of dd1 must be less than or equal to dd2.Nonconstant dimension-bound expressions can be used in a subprogram to define adjustable arrays, but not in a main program.
Noninteger dimension bound expressions are converted to integers before use. Any fractional part is truncated.
Adjustable Array
If the dimension declarator is an arithmetic expression that contains formal arguments or variables defined in the
COMMONstatement, then the array is called an adjustable array. In such cases, the dimension is equal to the initial value of the argument upon entry into the subprogram.Assumed-Size Array
The array is called an assumed-size array when the dimension declarator contains an asterisk. In such cases, the upper bound of that dimension is not stipulated. An asterisk can only appear for formal arrays and as the upper bound of the last dimension in an array declarator.
Examples
Example 1: Arrays in a main program:
DIMENSION M(4,4), V(1000)...ENDIn the above example,
Mis specified as an array of dimensions 4 ×4 andVis specified as an array of dimension 1000.Example 2: An adjustable array in a subroutine:
SUBROUTINE INV( M, N )DIMENSION M( N, N )...ENDIn the above example, the formal arguments are an array,
M, and a variableN.Mis specified to be a square array of dimensionsN×N.Example 3: Lower and upper bounds:
DIMENSION HELIO (-3:3, 4, 3:9)...ENDIn the above example,
HELIOis a 3-dimensional array. The first element isHELIO(-3,1,3)and the last element isHELIO(3,4,9).Example 4: Dummy array with lower and upper bounds:
SUBROUTINE ENHANCE( A, NLO, NHI )DIMENSION A(NLO : NHI)...ENDExample 5: Noninteger bounds
:
PARAMETER ( LO = 1, HI = 9.3 )DIMENSION A(HI, HI*3 + LO )...ENDIn the above example,
Ais an array of dimension 9×28.Example 6: Adjustable array with non-integer bounds:
SUBROUTINE ENHANCE( A, X, Y )DIMENSION A(X : Y)...ENDExample 7: Assumed-size arrays:
SUBROUTINE RUN(A,B,N)DIMENSION A(*), B(N,*)...
DOThe
DOstatement repeatedly executes a set of statements.where s is a statement number. The form of loop-control is
variable
=e1,e2[,e3]
Description
The
DOstatement contains the following constructs.Labeled
DOLoopA labeled
DOloop consists of the following:
DOstatement- Set of executable statements called a block
- Terminal statement, usually a
CONTINUEstatementTerminal Statement
The statement identified by s is called the terminal statement. It must follow the
DOstatement in the sequence of statements within the same program unit as theDOstatement.The terminal statement should not be one of the following statements:
- Unconditional
GOTO- Assigned
GOTO- Arithmetic
IF- Block
IF/ELSEIFELSEENDIFRETURNSTOPENDDOIf the terminal statement is a logical
IFstatement, it can contain any executable statement, except:
DO/DOWHILE- Block
IF/ELSEIFELSEIFELSEENDIFEND- Logical
IF
DOLoop RangeThe range of a
DOloop consists of all of the executable statements that appear following theDOstatement, up to and including the terminal statement.If a
DOstatement appears within the range of anotherDOloop, its range must be entirely contained within the range of the outerDOloop. More than one labeledDOloop can have the same terminal statement.If a
DOstatement appears within anIF,ELSE IF, orELSEblock, the range of the associatedDOloop must be contained entirely within that block.If a block
IFstatement appears within the range of aDOloop, the correspondingEND IFstatement must also appear within the range of thatDOloop.Block
DOLoop![]()
DOstatement- Set of executable statements called a block
- Terminal statement, an
ENDDOstatementExecution proceeds as follows:
1. The expressions e1, e2, and e3 are evaluated. If e3 is not present, its value is assumed to be one.2. TheDOvariable is initialized with the value of e1.3. The iteration count is established as the value of the expression:
MAX(INT((e2-e1+e3)/),e30)- The iteration count is zero if either of the following is true:
- e1 > e2 and e3 > zero.
- e1 < e2 and e3 < zero.
- If the
-onetripcompile time option is specified, then the iteration count is never less than one.4. The iteration count is tested, and, if it is greater than zero, the range of theDOloop is executed.Terminal Statement Processing
After the terminal statement of a
DOloop is executed, the following steps are performed:1. The value of theDOvariable, if any, is incremented by the value of e3 that was computed when theDOstatement was executed.2. The iteration count is decreased by one.3. The iteration count is tested, and if it is greater than zero, the statements in the range of theDOloop are executed again.Restrictions
The
DOvariable must not be modified in any way within the range of theDOloop.Control must not jump into the range of a
DOloop from outside its range.Comments
In some cases, the
DOvariable can overflow as a result of an increment that is performed prior to testing it against the final value. When this happens, your program has an error, and neither the compiler nor the runtime system detects it. In this situation, though theDOvariable wraps around, the loop can terminate properly.If there is a jump into the range of a
DOloop from outside its range, a warning is issued, but execution continues anyway.When the jump is from outside to the terminal statement that is
CONTINUE, and this statement is the terminal statement of several nestedDOloops, then the most innerDOloop is always executed.Examples
Example 1: Nested
DOloops:
The inner loop is not executed, and at the
WRITE,Lis undefined. HereLis shown as 0, but that is implementation-dependent; do not rely on it.Example 2: The program
DoNest2.f(DOvariable always defined):
INTEGER COUNT, OUTERCOUNT = 0DO OUTER = 1, 5NOUT = OUTERDO INNER = 1, 3NIN = INNERCOUNT = COUNT+1END DOEND DOWRITE(*,*) OUTER, NOUT, INNER, NIN, COUNTENDThe above program prints out:
6 5 4 3 15
DO WHILEThe
DOWHILEstatement repeatedly executes a set of statements while the specified condition is true.
DO[s[,]]WHILE(e)
Parameter Description s Label of an executable statement e Logical expression
Description
Execution proceeds as follows:
1. The specified expression is evaluated.2. If the value of the expression is true, the statements in the range of theDO WHILEloop are executed.3. If the value of the expression is false, control is transferred to the statement following theDO WHILEloop.Terminal Statement
If s is specified, the statement identified by it is called the terminal statement, and it must follow the
DOWHILEstatement. The terminal statement must not be one of the following statements:
- Unconditional
GOTO- Assigned
GOTO- Arithmetic
IF- Block
IF/ELSEIFELSEENDIFRETURNSTOPENDDO/DO WHILEIf the terminal statement is a logical
IFstatement, it can contain any executable statement, except:
DO/DO WHILE- Block
IF/ELSE IFELSEEND IFEND- Logical
IFIf s is not specified, the
DOWHILEloop must end with anENDDOstatement.
DO WHILELoop RangeThe range of a
DOWHILEloop consists of all the executable statements that appear following theDOWHILEstatement, up to and including the terminal statement.If a
DOWHILEstatement appears within the range of anotherDOWHILEloop, its range must be entirely contained within the range of the outerDOWHILEloop. More than oneDOWHILEloop can have the same terminal statement.If a
DOWHILEstatement appears within anIF,ELSEIF, orELSEblock, the range of the associatedDOWHILEloop must be entirely within that block.If a block
IFstatement appears within the range of aDO WHILEloop, the correspondingENDIFstatement must also appear within the range of thatDO WHILEloop.Terminal Statement Processing
After the terminal statement of a
DOWHILEloop is executed, control is transferred back to the correspondingDOWHILEstatement.Restrictions
Jumping into the range of a
DOWHILEloop from outside its range can produce unpredictable results.Comments
The variables used in the e can be modified in any way within the range of the
DOWHILEloop.Examples
Example 1: A
DOWHILEwithout a statement number:
INTEGER A(4,4), C, R...C = 4R = 1DO WHILE ( C .GT. R )A(C,R) = 1C = C - 1END DOExample 2: A
DOWHILEwith a statement number:
INTEGER A(4,4), C, R...DO 10 WHILE ( C .NE. R )A(C,R) = A(C,R) + 1C = C+110 CONTINUE
DOUBLE COMPLEXThe
DOUBLECOMPLEXstatement specifies the type to be double complex. It optionally specifies array dimensions and size, and initializes with values.
DOUBLECOMPLEXv[/c/][,v[/c/]...
Parameter Description v Name of a symbolic constant, variable, array, array declarator, function, or dummy function c List of constants for the immediately preceding name
Description
The declaration can be:
DOUBLE COMPLEXorCOMPLEX*16.
DOUBLECOMPLEX![]()
For a declaration such as
DOUBLE COMPLEX Z, the variableZis twoREAL*8elements contiguous in memory, interpreted as one double-width complex number.If you do not specify the size, a default size is used.
The default size, for a declaration such as
DOUBLECOMPLEXZ, can be altered by compiling with any of the options-dbl,-r8, or-xtypemap. See the discussion in Chapter 2 for details.
COMPLEX*16![]()
For a declaration such as
COMPLEX*16 Z, the variableZis always twoREAL*8elements contiguous in memory, interpreted as one double-width complex number.Comments
There is a double-complex version of each complex built-in function. Generally, the specific function names begin with
ZorCDinstead ofC, except for the two functions,DIMAGandDREAL, which return a real value. Examples are:SIN(),CSIN(),CDSIN().Example: Double-complex scalars and arrays:
DOUBLE COMPLEX U, VDOUBLE COMPLEX W(3,6)COMPLEX*16 X, Y(5,5)COMPLEX U*16(5), V(5)*16
DOUBLE PRECISIONThe
DOUBLEPRECISIONstatement specifies the type to be double precision, and optionally specifies array dimensions and initializes with values.
DOUBLEPRECISIONv[/c/][,v[/c/]...
Parameter Description v Name of a symbolic constant, variable, array, array declarator, function, or dummy function c List of constants for the immediately preceding name
Description
The declaration can be:
DOUBLE PRECISIONorREAL*8.
DOUBLE PRECISIONFor a declaration such as
DOUBLEPRECISIONX, the variableXis aREAL*8element in memory, interpreted as one double-width real number.If you do not specify the size, a default size is used. The default size, for a declaration such as
DOUBLE PRECISION X, can be altered by compiling with any of the options-dbl,-r8, or-xtypemap. See the discussion in Chapter 2 for details.
REAL*8![]()
For a declaration such as
REAL*8 X, the variableXis always an element of typeREAL*8in memory, interpreted as a double-width real number.Example
DOUBLE PRECISION R, S(3,6)REAL*8 T(-1:0,5)
ELSEThe
ELSEstatement indicates the beginning of anELSEblock.where e is a logical expression.
Description
Execution of an
ELSEstatement has no effect on the program.An
ELSEblock consists of all the executable statements following theELSEstatements, up to but not including the nextEND IFstatement at the sameIFlevel as theELSEstatement. See IF (Block) for more information.Restrictions
You cannot jump into an
ELSEblock from outside theELSEblock.The statement label, if any, of an
ELSEstatement cannot be referenced by any statement.A matching
END IFstatement of the sameIFlevel as theELSEmust appear before anyELSE IForELSEstatement at the sameIFlevel.Examples
Example 1:
ELSE:
CHARACTER S...IF ( S .GE. '0' .AND. S .LE. '9' ) THENCALL PUSHELSECALL TOLOWEREND IF...Example 2: An invalid
ELSEIFwhere anENDIFis expected:
IF ( K .GT. 5 ) THENN = 1ELSEN = 0ELSE IF ( K .EQ. 5 ) THEN Incorrect...
ELSE IFThe
ELSEIFprovides a multiple alternative decision structure.where e1 and e2 are logical expressions.
Description
You can make a series of independent tests, and each test can have its own sequence of statements.
An
ELSEIFblock consists of all the executable statements following theELSEIFstatement up to, but not including, the nextELSEIF,ELSE, orENDIFstatement at the sameIFlevel as theELSEIFstatement.An
ELSEIFblock can be empty.Execution of the
ELSEIF(e)proceeds as follows, depending on the value of the logical expression, e:1. e is evaluated.2. If e is true, execution continues with the first statement of theELSE IFblock. If e is true and theELSE IFblock is empty, control is transferred to the nextEND IFstatement at the sameIFlevel as theELSE IFstatement.3. If e is false, control is transferred to the nextELSE IF,ELSE, orEND IFstatement at the sameIFlevel as theELSE IFstatement.Restrictions
You cannot jump into an
ELSEIFblock from outside theELSE IFblock.The statement label, if any, of an
ELSE IFstatement cannot be referenced by any statement.A matching
END IFstatement of the sameIFlevel as theELSE IFmust appear before anyELSE IForELSEstatement at the sameIFlevel.Example
Example:
ELSEIF:
READ (*,*) NIF ( N .LT. 0 ) THENWRITE(*,*) 'N<0'ELSE IF ( N .EQ. 0) THENWRITE(*,*) 'N=0'ELSEWRITE(*,*) 'N>0'END IF
ENCODE/DECODEThe
ENCODEstatement writes data from a list to memory.
ENCODE(size,f,buf[, IOSTAT=ios] [, ERR=s]) [iolist]
Description
ENCODEis provided for compatibility with older versions of FORTRAN. Similar functionality can be accomplished using internal files with a formatted sequentialWRITEstatement.ENCODEis not in the FORTRAN 77 Standard.Data are edited according to the format identifier.
Example
CHARACTER S*6, T*6INTEGER V(3)*4DATA S / '987654' /DECODE( 6, 1, S ) V1 FORMAT( 3 I2 )ENCODE( 6, 1, T ) V(3), V(2), V(1)The
DECODEreads the characters ofSas 3 integers, and stores them intoV(1),V(2), andV(3). TheENCODEstatement writes the valuesV(3),V(2), andV(1), intoTas characters;Tthen contains'547698'.See DECODE/ENCODE for more information and a full example.
ENDThe
ENDstatement indicates the end of a program unit with the following syntax:
ENDDescription
- Must be the last statement in the program unit.
- Must be the only statement in a line.
- Can have a label.
In a main program, an
ENDstatement terminates the execution of the program. In a function or subroutine, it has the effect of aRETURN.![]()
In the FORTRAN 77 Standard, the
ENDstatement cannot be continued, butf77allows this practice.![]()
No other statement, such as an
ENDIFstatement, can have an initial line that appears to be anENDstatement.Example
Example:
END:
PROGRAM MAINWRITE( *, * ) 'Very little'END
END DOThe
ENDDOstatement terminates a
DOloop and requires the following syntax:
END DODescription
The
ENDDOstatement is the delimiting statement of a BlockDOstatement. If the statement label is not specified in aDOstatement, the corresponding terminating statement must be anENDDOstatement. You can branch to anENDDOstatement only from within the range of theDOloop that it terminates.Examples
Example 1: A
DOloop with a statement number:
DO 10 N = 1, 100...10 END DOExample 2: A
DOloop without statement number:
DO N = 1, 100...END DO
END FILEThe
ENDFILEstatement writes an end-of-file record as the next record of the file connected to the specified unit.
END FILE ([UNIT= ]u[, IOSTAT=ios] [, ERR=s])
Description
If you are using the
ENDFILEstatement and other standard FORTRAN I/O for tapes, we recommend that you use theTOPEN()routines instead, because they are more reliable.Two endfile records signify the end-of-tape mark. When writing to a tape file,
ENDFILEwrites two endfile records, then the tape backspaces over the second one. If the file is closed at this point, both end-of-file and end-of-tape are marked. If more records are written at this point, either by continued write statements or by another program if you are using no-rewind magnetic tape, the first tape mark stands (endfile record), and is followed by another data file, then by more tape marks, and so on.Restrictions
u must be connected for sequential access. Execution of an
ENDFILEstatement on a direct-access file is not defined in the FORTRAN 77 Standard, and is unpredictable. Do not use anENDFILEstatement on a direct-access file.Examples
Example 1: Constants:
END FILE 2END FILE ( 2 )END FILE ( UNIT=2 )Example 2: Variables:
LOGUNIT = 2END FILE LOGUNITEND FILE ( LOGUNIT )END FILE ( UNIT=LOGUNIT )Example 3: Error trap:
NOUT = 2END FILE ( UNIT=NOUT, IOSTAT=KODE, ERR=9)...9 WRITE(*,*) 'Error at END FILE, on unit', NOUTSTOP
END IFThe
ENDIFstatement ends the blockIFthat theIFbegan and requires the following syntax:
END IFDescription
For each block
IFstatement there must be a correspondingENDIFstatement in the same program unit. AnENDIFstatement matches if it is at the sameIFlevel as the blockIFstatement.Examples
Example 1:
:IF/ENDIF
IF ( N .GT. 0 )THENN = N+1END IFExample 2:
IF/ELSE/ENDIF:
IF ( N .EQ. 0 ) THENN = N+1ELSEN = N-1END IF
END MAPThe
ENDMAPstatement terminates the
MAPdeclaration and requires the following syntax:
END MAPDescription
See UNION and MAP for more information.
Restrictions
The
MAPstatement must be within aUNIONstatement.Example
...MAPCHARACTER *16 MAJOREND MAP...
END STRUCTUREThe
ENDSTRUCTUREstatement terminates the
STRUCTUREstatement and requires the following syntax:
END STRUCTUREDescription
See STRUCTURE for more information.
Example
STRUCTURE /PROD/INTEGER*4 IDCHARACTER*16 NAMECHARACTER*8 MODELREAL*4 COSTREAL*4 PRICEEND STRUCTURE
END UNIONThe
ENDUNIONstatement terminates the
UNIONstatement and requires the following syntax:
END UNIONDescription
See UNION and MAP for more information.
Example
UNIONMAPCHARACTER*16END MAPMAPINTEGER*2 CREDITSCHARACTER *8 GRAD_DATEEND MAPEND UNION
ENTRYThe
ENTRYstatement defines an alternate entry point within a subprogram.
ENTRYen[([fa[,fa]...])]
Description
Note these nuances for the
ENTRYstatement:Procedure References by Entry Names
An
ENTRYname used in a subroutine subprogram is treated like a subroutine and can be referenced with aCALLstatement. Similarly, theENTRYname used in a function subprogram is treated like a function and can be referenced as a function reference.An entry name can be specified in an
EXTERNALstatement and used as an actual argument. It cannot be used as a dummy argument.Execution of an
ENTRYsubprogram (subroutine or function) begins with the first executable statement after theENTRYstatement.The
ENTRYstatement is a nonexecutable statement.The entry name cannot be used in the executable statements that physically precede the appearance of the entry name in an
ENTRYstatement.Argument Correspondence
The formal arguments of an
ENTRYstatement need not be the same in order, number, type, and name as those forFUNCTION,SUBROUTINE, and otherENTRYstatements in the same subprogram. Each reference to a function, subroutine, or entry must use an actual argument list that agrees in order, number, type, and name with the dummy argument list in the correspondingFUNCTION,SUBROUTINE, orENTRYstatement.Alternate return arguments in
ENTRYstatements can be specified by placing asterisks in the dummy argument list. Ampersands are valid alternates.![]()
ENTRYstatements that specify alternate return arguments can be used only in subroutine subprograms, not functions.Restrictions
An
ENTRYstatement cannot be used within a blockIFconstruct or aDOloop.If an
ENTRYstatement appears in a character function subprogram, it must be defined as typeCHARACTERwith the same length as that of a function subprogram.Examples
Example 1: Multiple entry points in a subroutine
:
SUBROUTINE FIN( A, B, C )INTEGER A, BCHARACTER C*4...RETURNENTRY HLEP( A, B, C )...RETURNENTRY MOOZ...RETURNENDIn the above example, the subroutine
FINhas two alternate entries: the entryHLEPhas an argument list; the entryMOOZhas no argument list.Example 2: In the calling routine, you can call the above subroutine and entries as follows:
INTEGER A, BCHARACTER C*4...CALL FIN( A, B, C )...CALL MOOZ...CALL HLEP( A, B, C )...In the above example, the order of the call statements need not match the order of the entry statements.
Example 3: Multiple entry points in a function:
REAL FUNCTION F2 ( X )F2 = 2.0 * XRETURNENTRY F3 ( X )F3 = 3.0 * XRETURNENTRY FHALF ( X )FHALF = X / 2.0RETURNEND
EQUIVALENCEThe
EQUIVALENCEstatement specifies that two or more variables or arrays in a program unit share the same memory.
EQUIVALENCE (nlist) [, (nlist)]...
Parameter Description nlist List of variable names, array element names, array names, and character substring names separated by commas
Description
An
EQUIVALENCEstatement stipulates that the storage sequence of the entities whose names appear in the list nlist must have the same first memory location.An
EQUIVALENCEstatement can cause association of entities other than specified in the nlist.An array name, if present, refers to the first element of the array.
If an array element name appears in an
EQUIVALENCEstatement, the number of subscripts can be less than or equal to the number of dimensions specified in the array declarator for the array name.Restrictions
In nlist, dummy arguments and functions are not permitted.
Subscripts of array elements must be integer constants greater than the lower bound and less than or equal to the upper bound.
EQUIVALENCEcan associate automatic variables only with other automatic variables or undefined storage classes. These classes must be ones which are not in any of theCOMMON,STATIC,SAVE,DATA, or dummy arguments.An
EQUIVALENCEstatement can associate an element of type character with a noncharacter element.![]()
An
EQUIVALENCEstatement cannot specify that the same storage unit is to occur more than once in a storage sequence. For example, the following statement is not allowed:
DIMENSION A (2)EQUIVALENCE (A(1),B), (A(2),B)An
EQUIVALENCEstatement cannot specify that consecutive storage units are to be nonconsecutive. For example, the following statement is not allowed:
REAL A (2)DOUBLE PRECISION D (2)EQUIVALENCE (A(1), D(1)), (A(2), D(2))When
COMMONstatements andEQUIVALENCEstatements are used together, several additional rules can apply. For such rules, refer to the notes on theCOMMONstatement.Example
CHARACTER A*4, B*4, C(2)*3EQUIVALENCE (A,C(1)),(B,C(2))The association of
A,B, andCcan be graphically illustrated as follows. The first seven character positions are arranged in memory as follows:
01 02 03 04 05 06 07 A A(1) A(2) A(3) A(4) B B(1) B(2) B(3) B(4) C C(1)(1) C(1)(2) C(1)(3) C(2)(1) C(2)(2) C(2)(3)
EXTERNALThe
EXTERNALstatement specifies procedures or dummy procedures as external, and allows their symbolic names to be used as actual arguments.
EXTERNALproc[,proc]...
Parameter Description proc Name of external procedure, dummy procedure, or block data routine.
Description
If an external procedure or a dummy procedure is an actual argument, it must be in an
EXTERNALstatement in the same program unit.If an intrinsic function name appears in an
EXTERNALstatement, that name refers to some external subroutine or function. The corresponding intrinsic function is not available in the program unit.Restrictions
A subroutine or function name can appear in only one of the
EXTERNALstatements of a program unit.A statement function name must not appear in an
EXTERNALstatement.Examples
Example 1: Use your own version of
TAN:
EXTERNAL TANT = TAN( 45.0 )...ENDFUNCTION TAN( X )...RETURNENDExample 2: Pass a user-defined function name as an argument:
REAL AREA, LOW, HIGHEXTERNAL FCN...CALL RUNGE ( FCN, LOW, HIGH, AREA )...ENDFUNCTION FCN( X )...RETURNENDSUBROUTINE RUNGE ( F, X0, X1, A )...RETURNEND
FORMATThe
FORMATstatement specifies the layout of the input or output records.label
FORMAT(f)
Parameter Description label Statement number f Format specification list
The repeatable edit descriptors are:
Iw
IIw.dOw
OOw.dZw
ZZw.dFw
FFw.dAw
ALw
LEw
EEw.dEw.d.eEew.dEDw
DDw.dDw.d.eDw.dEeGw
GGw.dGw.d.eGw.dEe
I,O,Zare for integers (decimal, octal, hex)F,E,D,Gare for reals (fixed-point, exponential, double, general)Ais for charactersLis for logicalsThe nonrepeatable edit descriptors are:
- 'a1a2 ... an' single quote-delimited character string
- "a1a2 ... an" double quote-delimited character string
- n
Ha1a2 ... an Hollerith string$/:- [k]
R(k defaults to 10)- [k]
P(k defaults to 0)B,BN, andBZS,SU,SP, andSSTn and nTTL[n] andTR[n] (n defaults to 1)- [n]
X(n defaults to 1)See Formatted I/O for full details of these edit descriptors.
Description
The
FORMATstatement includes the explicit editing directives to produce or use the layout of the record. It is used with formatted input/output statements andENCODE/DECODEstatements.Repeat Factor
r must be a nonzero, unsigned, integer constant.
Repeatable Edit Descriptors
The descriptors
I,O,Z,F,E,D,G,L, andAindicate the manner of editing and are repeatable.w and e are nonzero, unsigned integer constants.
d and m are unsigned integer constants.
Nonrepeatable Edit Descriptors
The descriptors are the following:
("),($),('),(/),(:),B,BN,BZ,H,P,R,Q,S,SU,SP,SS,T,TL,TR,XThese descriptors indicate the manner of editing and are not repeatable:
- Each ai is any ASCII character.
- n is a nonzero, unsigned integer constant.
- k is an optionally signed integer constant.
Item Separator
Items in the format specification list are separated by commas. A comma can be omitted before or after the slash and colon edit descriptors, between a
Pedit descriptor, and the immediately followingF,E,D, orGedit descriptors.In some sense, the comma can be omitted anywhere the meaning is clear without it, but, other than those cases listed above, this is nonstandard. u
Variable Format Expressions
![]()
In general, any integer constant in a format can be replaced by an arbitrary expression enclosed in angle brackets:
1 FORMAT( ... <e> ... )The n in an n
H... edit descriptor cannot be a variable format expression.Restrictions
The
FORMATstatement label cannot be used in aGOTO,IF-arithmetic,DO, or alternate return.Warnings
For explicit formats, invalid format strings cause warnings or error messages at compile time.
For formats in variables, invalid format strings cause warnings or error messages at runtime.
For variable format expressions, of the form
<e>, invalid format strings cause warnings or error messages at compile time or runtime.See Runtime Formats for details.
Examples
Example 1: Some
A,I, andFformats:
READ( 2, 1 ) PART, ID, HEIGHT, WEIGHT1 FORMAT( A8, 2X, I4, F8.2, F8.2 )WRITE( 9, 2 ) PART, ID, HEIGHT, WEIGHT2 FORMAT( 'Part:', A8, ' Id:', I4, ' Height:', F8.2,& ' Weight:', F8.2 )Example 2: Variable format expressions:
DO 100 N = 1, 50...1 FORMAT( 2X, F<N+1>.2 )
FUNCTION(External)The
FUNCTIONstatement identifies a program unit as a function subprogram.
[type]FUNCTIONfun([ar[,ar]...])
(
COMPLEX*32andREAL*16are SPARC only.)An alternate nonstandard syntax for length specifier is as follows:
![]()
[type]FUNCTIONfun[*m]([ar[,ar]...])
Parameter Description m Unsigned, nonzero integer constant specifying length of the data type. ar Formal argument name
Description
Note the type, value, and formal arguments for a
FUNCTIONstatement.Type of Function
The function statement involves type, name, and formal arguments.
If type is not present in the
FUNCTIONstatement, then the type of the function is determined by default and by any subsequentIMPLICITor type statement. If type is present, then the function name cannot appear in other type statements.
Note Compiling with any of the options-dbl,-r8,-i2, or-xtypemapcan alter the default data size assumed in the call to or definition of functions unless the data type size is explicitly declared. See Chapter 2 and the Fortran User Guide for details on these options.
Value of Function
The symbolic name of the function must appear as a variable name in the subprogram. The value of this variable, at the time of execution of the
RETURNorENDstatement in the function subprogram, is the value of the function.Formal Arguments
The list of arguments defines the number of formal arguments. The type of these formal arguments is defined by some combination of default, type statements,
IMPLICITstatements, andDIMENSIONstatements.The number of formal arguments must be the same as the number of actual arguments at the invocation of this function subprogram.
A function can assign values to formal arguments. These values are returned to the calling program when the
RETURNorENDstatements are executed in the function subprogram.Restrictions
Alternate return specifiers are not allowed in
FUNCTIONstatements.
f77provides recursive calls. A function or subroutine is called recursively if it calls itself directly. If it calls another function or subroutine, which in turn calls this function or subroutine before returning, then it is also called recursively.Examples
Example 1: Character function:
CHARACTER*5 FUNCTION BOOL(ARG)BOOL = 'TRUE'IF (ARG .LE. 0) BOOL = 'FALSE'RETURNENDIn the above example,
BOOLis defined as a function of typeCHARACTERwith a length of 5 characters. This function when called returns the string,TRUEorFALSE, depending on the value of the variable,ARG.Example 2: Real function:
FUNCTION SQR (A)SQR = A*ARETURNENDIn the above example, the function
SQRis defined as function of typeREALby default, and returns the square of the number passed to it.Example 3: Size of function, alternate syntax:
INTEGER FUNCTION FCN*2 ( A, B, C )The above nonstandard form is treated as:
INTEGER*2 FUNCTION FCN ( A, B, C )
GO TO(Assigned)The assigned
GOTOstatement branches to a statement label identified by the assigned label value of a variable.
GO TOi[[,](s[,s]...)]
Parameter Description i Integer variable name s Statement label of an executable statement
Description
Execution proceeds as follows:
1. At the time an assignedGOTOstatement is executed, the variable i must have been assigned the label value of an executable statement in the same program unit as the assignedGOTOstatement.2. If an assignedGOTOstatement is executed, control transfers to a statement identified by i.3. If a list of statement labels is present, the statement label assigned to i must be one of the labels in the list.Restrictions
i must be assigned by an
ASSIGNstatement in the same program unit as theGOTOstatement.i must be
INTEGER*4orINTEGER*8, notINTEGER*2.s must be in the same program unit as the
GOTOstatement.The same statement label can appear more than once in a
GOTOstatement.The statement control jumps to must be executable, not
DATA,ENTRY,FORMAT, orINCLUDE.Control cannot jump into a
DO,IF,ELSEIF, orELSEblock from outside the block.Example
Example: Assigned
GOTO:
ASSIGN 10 TO N...GO TO N ( 10, 20, 30, 40 )...10 CONTINUE...40 STOP
GO TO(Computed)The computed
GOTOstatement selects one statement label from a list, depending on the value of an integer or real expression, and transfers control to the selected one.
GO TO (s[,s]...)[,]e
Parameter Description s Statement label of an executable statement e Expression of type integer or real
Description
Execution proceeds as follows:
1. e is evaluated first. It is converted to integer, if required.2. If 1e
n, where n is the number of statement labels specified, then the eth label is selected from the specified list and control is transferred to it.
3. If the value of e is outside the range, that is, e < 1 or e > n, then the computedGO TOstatement serves as aCONTINUEstatement.Restrictions
s must be in the same program unit as the
GOTOstatement.The same statement label can appear more than once in a
GOTOstatement.The statement control jumps to must be executable, not
DATA,ENTRY,FORMAT, orINCLUDE.Control cannot jump into a
DO,IF,ELSEIF, orELSEblock from outside the block.Example
Example: Computed
:GOTO
...GO TO ( 10, 20, 30, 40 ), N...10 CONTINUE...20 CONTINUE...40 CONTINUE
- If
Nequals one, then go to 10.- If
Nequals two, then go to 20.- If
Nequals three, then go to 30.- If
Nequals four, then go to 40.- If
Nis less than one orNis greater than four, then fall through to 10.
GO TO(Unconditional)The unconditional
GOTOstatement transfers control to a specified statement.
GO TOs
Parameter Description s Statement label of an executable statement
Description
Execution of the
GOTOstatement transfers control to the statement labeled s.Restrictions
s must be in the same program unit as the
GOTOstatement.The statement control jumps to must be executable, not a
DATA,ENTRY,FORMAT, orINCLUDEstatement.Control cannot jump into a
DO,IF,ELSEIF, orELSEblock from outside the block.Example
A = 100.0B = 0.01GO TO 90...90 CONTINUE
IF(Arithmetic)The arithmetic
IFstatement branches to one of three specified statements, depending on the value of an arithmetic expression.
IF(e)s1,s2,s3
Parameter Description e Arithmetic expression: integer, real, double precision, or quadruple precision s1, s2, s3 Labels of executable statements
Description
The
IFstatement transfers control to the first, second, or third label if the value of the arithmetic expression is less than zero, equal to zero, or greater than zero, respectively.
- The s1, s2, s3 must be in the same program unit as the
IFstatement.- The same statement label can appear more than once in a
IFstatement.- The statement control jumps to must be executable, not
DATA,ENTRY,FORMAT, orINCLUDE.- Control cannot jump into a
DO,IF,ELSEIF, orELSEblock from outside the block.Example
N = 0IF ( N ) 10, 20, 30Since the value of
Nis zero, control is transferred to statement label20.
IF(Block)The block
IFstatement executes one of two or more sequences of statements, depending on the value of a logical expression.
...
END IF
Parameter Description e A logical expression
Description
The block
IFstatement evaluates a logical expression and, if the logical expression is true, it executes a set of statements called theIFblock. If the logical expression is false, control transfers to the nextELSE,ELSEIF, orENDIFstatement at the sameIF-level.
IF-LevelThe
IF-level of a statement S is the value n1-n2, where n1 is the number of blockIFstatements from the beginning of the program unit up to the end, including S; n2 is the number ofENDIFstatements in the program unit up to, but not including, S.Example: In the following program, the
:IF-level of statement 9 is 2-1, or, 1
IF ( X .LT. 0.0 ) THENMIN = NODEEND IF...9 IF ( Y .LT. 0.0 ) THENMIN = NODE - 1END IFThe
IF-level of every statement must be zero or positive. TheIF-level of each blockIF,ELSEIF,ELSE, andENDIFstatement must be positive. TheIF-level of theENDstatement of each program unit must be zero.
IFBlockAn
IFblock consists of all the executable statements following the blockIFstatement, up to, but not including, the nextELSE,ELSEIF, orENDIFstatement that has the sameiflevel as the blockIFstatement. AnIFblock can be empty. In the following example, the two assignment statements form anIFblock:
IF ( X .LT. Y ) THENM = 0N = N+1END IFExecution proceeds as follows:
1. The logical expression e is evaluated first. If e is true, execution continues with the first statement of theIFblock.2. If e is true and theIFblock is empty, control is transferred to the nextENDIFstatement with the sameIF-level as the blockIFstatement.3. If e is false, control is transferred to the nextELSE IF,ELSE, orEND IFstatement with the sameIF-level as the blockIFstatement.4. If the last statement of theIFblock does not result in a branch to a label, control is transferred to the nextEND IFstatement that has the sameIF-level as the blockIFstatement preceding theIFblock.Restrictions
Control cannot jump into an
IFblock from outside theIFblock.Examples
Example 1:
IF-THEN-ELSE:
IF ( L ) THENN=N+1CALL CALCELSEK=K+1CALL DISPEND IFExample 2:
IF-THEN-ELSE-IFwithELSE-IF:
IF ( C .EQ. 'a' ) THENNA=NA+1CALL APPENDELSE IF ( C .EQ. 'b' ) THENNB=NB+1CALL BEFOREELSE IF ( C .EQ. 'c' ) THENNC=NC+1CALL CENTEREND IFExample 3: Nested
IF-THEN-ELSE:
IF ( PRESSURE .GT 1000.0 ) THENIF ( N .LT. 0.0 ) THENX = 0.0Y = 0.0ELSEZ = 0.0END IFELSE IF ( TEMPERATURE .GT. 547.0 ) THENZ = 1.0ELSEX = 1.0Y = 1.0END IF
IF(Logical)The logical
IFstatement executes one single statement, or does not execute it, depending on the value of a logical expression.
IF(e)st
Parameter Description e Logical expression st Executable statement
Description
The logical IF statement evaluates a logical expression and executes the specified statement if the value of the logical expression is true. The specified statement is not executed if the value of the logical expression is false, and execution continues as though a
CONTINUEstatement had been executed.st can be any executable statement, except a
DOblock,IF,ELSEIF,ELSE,ENDIF,END, or another logicalIFstatement.Example
IF ( VALUE .LE. ATAD ) CALL PUNT ! Note that there is no THEN.IF ( TALLY .GE. 1000 ) RETURN
IMPLICITThe
IMPLICITstatement confirms or changes the default type of names.
IMPLICITtype(a[,a]...) [,type(a[,a]...)]
IMPLICIT UNDEFINED(A-Z)u
Description
The different uses for implicit typing and no implicit typing are described here.
Implicit Typing
The
IMPLICITstatement can also indicate that no implicit typing rules apply in a program unit.An
IMPLICITstatement specifies a type and size for all user-defined names that begin with any letter, either a single letter or in a range of letters, appearing in the specification.An
IMPLICITstatement does not change the type of the intrinsic functions.An
IMPLICITstatement applies only to the program unit that contains it.A program unit can contain more than one
IMPLICITstatement.
IMPLICITtypes for particular user names are overridden by a type statement.
Note Compiling with any of the options-dbl,-i2, -r8, or-xtypemapcan alter the assumed size of names typed with anIMPLICITstatement that does not specify a size:IMPLICIT REAL (A-Z). See Chapter 2 and the Fortran User's Guide for details.
No Implicit Typing
The second form of
IMPLICITspecifies that no implicit typing should be done for user-defined names, and all user-defined names shall have their types declared explicitly.If either
IMPLICITNONEorIMPLICITUNDEFINED(A-Z)is specified, there cannot be any otherIMPLICITstatement in the program unit.Restrictions
IMPLICITstatements must precede all other specification statements.The same letter can appear more than once as a single letter, or in a range of letters in all
IMPLICITstatements of a program unit.![]()
The FORTRAN 77 Standard restricts this usage to only once. For
f77, if a letter is used twice, each usage is declared in order. See Example 4.Examples
Example 1:
IMPLICIT: everything is integer:
IMPLICIT INTEGER (A-Z)X = 3K = 1STRING = 0Example 2: Complex if it starts with
U,V, orW; character if it starts withCorS:
IMPLICIT COMPLEX (U,V,W), CHARACTER*4 (C,S)U1 = ( 1.0, 3.0)STRING = 'abcd'I = 0X = 0.0Example 3: All items must be declared:
IMPLICIT NONECHARACTER STR*8INTEGER NREAL YN = 100Y = 1.0E5STR = 'Length'In the above example, once
IMPLICITNONEis specified in the beginning. All the variables must be declared explicitly.Example 4: A letter used twice:
![]()
IMPLICIT INTEGER (A-Z)IMPLICIT REAL (A-C)C = 1.5E8D = 9In the above example,
DthroughZimpliesINTEGER, andAthroughCimpliesREAL.
INCLUDEThe
INCLUDEstatement inserts a file into the source program.
INCLUDE 'file'
Parameter Description file Name of the file to be inserted
Description
The contents of the named file replace the
INCLUDEstatement.Search Path
If the name referred to by the
INCLUDEstatement begins with the character/, then it is taken byf77to mean the absolute path name of theINCLUDEfile. Otherwise,f77looks for the file in the following directories, in this order:
- The directory that contains the source file with the
INCLUDEstatement- The directories that are named in the
-Iloc options- The current directory in which the
f77command was issued- The directories in the default list., the default list is:
These
INCLUDEstatements can be nested ten deep.Preprocessor
#includeThe paths and order searched for the
INCLUDEstatement are not the same as those searched for the preprocessor#includedirective, described under-Iin the Fortran User's Guide. Files included by the preprocessor#includedirective can contain#definesand the like; files included with the compilerINCLUDEstatement must contain only FORTRAN statements.VMS Logical File Names in the
INCLUDEStatement
f77interprets VMS logical file names on theINCLUDEstatement if:
- The
-xl[d]or-vax=spec compiler options are set.- The environment variable
LOGICALNAMEMAPPINGis there to define the mapping between the logical names and the UNIX path name.
f77uses the following rules for the interpretation:
- where each lname is a logical name and each path1, path2, and so forth is the path name of a directory (without a trailing
/).
- All blanks are ignored when parsing this string. It strips any trailing
/[no]list from the file name in theINCLUDEstatement.- Logical names in a file name are delimited by the first : in the VMS file name, so
f77converts file names of the lname1:file form to the path1/file form.- For logical names, uppercase and lowercase are significant. If a logical name is encountered on the
INCLUDEstatement which is not specified in theLOGICALNAMEMAPPING, the file name is used, unchanged.Examples
Example 1:
INCLUDE, simple case:
INCLUDE 'stuff'The above line is replaced by the contents of the file stuff.
Example 2:
INCLUDE, search paths:
- Your source file has the line:
INCLUDE 'ver1/const.h'- Your current working directory is
/usr/ftn.- Your source file is
/usr/ftn/projA/myprg.f.In this example,
f77seeksconst.hin these directories, in the order shown.For a standard install,
f77searches these directories:
/usr/ftn/projA/ver1/usr/ftn/ver1/opt/SUNWspro/<release>/include/f77/ver1/usr/includeFor a non-standard install to a directory /mydir, replace
/optwith /mydir. The <release> path changes with each compiler release.
INQUIREThe
INQUIREstatement returns information about a unit or file.
INQUIRE(FILE=fn,slist)
Description
You can determine such things about a file as whether it exists, is opened, or is connected for sequential I/O. That is, files have such attributes as name, existence (or nonexistence), and the ability to be connected in certain ways (
FORMATTED,UNFORMATTED,SEQUENTIAL, orDIRECT).Inquire either by unit or by file, but not by both in the same statement.
In this system environment, the only way to discover what permissions you have for a file is to use the
ACCESS(3F) function. TheINQUIREstatement does not determine permissions.The following table summarizes the
INQUIREspecifiers:
*indicates non-standard for inquire-by-unit, but accepted byf77.indicates non-standard for inquire-by-file, but accepted byf77.
- If a file is scratch, then
NAMEDandNUMBERare not returned.- If there is no file with the specified name, then these variables are not returned:
DIRECT,FORMATTED,NAME,NAMED,SEQUENTIAL, andUNFORMATTED.- If
OPENED=.FALSE., then these variables are not returned:ACCESS,BLANK,FORM,NEXTREC, andRECL.- If no file is connected to the specified unit, then these variables are not returned:
ACCESS,BLANK,DIRECT,FORM,FORMATTED,NAME,NAMED,NEXTREC,NUMBER,RECL,SEQUENTIAL, andUNFORMATTED.- If
ACCESS='SEQUENTIAL', then these variables are not returned:RECLandNEXTREC.- If
FORM='UNFORMATTED', thenBLANKis not returned.
INQUIRESpecifier KeywordsThe following provides a detailed list of the
INQUIREspecifier keywords:ACCESS=acc
- acc is a character variable that is assigned the value
'SEQUENTIAL'if the connection is for sequential I/O and'DIRECT'if the connection is for direct I/O. The value is undefined if there is no connection.BLANK=blnk
- blnk is a character variable that is assigned the value
'NULL'if null blank control is in effect for the file connected for formatted I/O, and'ZERO'if blanks are being converted to zeros and the file is connected for formatted I/O.DIRECT=dir
- dir is a character variable that is assigned the value
'YES'if the file could be connected for direct I/O,'NO'if the file could not be connected for direct I/O, and'UNKNOWN'if the system can't tell.ERR=s
- s is a statement label of a statement to branch to if an error occurs during the execution of the
INQUIREstatement.EXIST=ex
- ex is a logical variable that is set to
.TRUE.if the file or unit exists, and.FALSE.otherwise. If the file is a link,INQUIREalways returns.TRUE., even if the linked file does not exist.FILE=fn
- n is a character expression or * with the name of the file. Trailing blanks in the file name are ignored. If the file name is all blanks, that means the current directory. The file need not be connected to a unit in the current program.
FORM=fm
- fm is a character variable which is assigned the value
'FORMATTED'if the file is connected for formatted I/O,'UNFORMATTED'if the file is connected for unformatted I/O,'BINARY'if the file was opened for unstructured binary I/O.
FORMATTED=fmt
- fmt is a character variable that is assigned the value
'YES'if the file could be connected for formatted I/O,'NO'if the file could not be connected for formatted I/O, and'UNKNOWN'if the system cannot tell.IOSTAT=ios
- ios is as in the
OPENstatement.NAME=fn
- fn is a character variable that is assigned the name of the file connected to the unit. If you do an inquire-by-unit, the name parameter is undefined, unless both the values of the
OPENEDandNAMEDvariables are both true. If you do an inquire by file, the name parameter is returned, even though the FORTRAN 77 Standard leaves it undefined.NAMED=nmd
- nmd is a logical variable that is assigned
.TRUE.if the file has a name,.FALSE.otherwise.NEXTREC=nr
- nr is an integer variable that is assigned one plus the number of the last record read from a file connected for direct access. If the file is not connect, -1 is returned in nr.
NUMBER=num
- num is an integer variable that is set to the number of the unit connected to the file, if any. If no file is connected, num is set to -1.
OPENED=od
- od is a logical variable that is set to
.TRUE.if the file is connected to a unit or the unit is connected to a file, and.FALSE.otherwise.RECL=rcl
- rcl is an integer variable that is assigned the record length of the records in the file if the file is connected for direct access.
f77does not adjust the rcl returned byINQUIRE. TheOPENstatement does such an adjustment if the-xl[d]option is set. See Details of Features That Require -xl[d] for an explanation of-xl[d]. If no file is connected, rcl is set to -1.SEQUENTIAL=seq
- seq is a character variable that is assigned the value
'YES'if the file could be connected for sequential I/O,'NO'if the file could not be connected for sequential I/O, and'UNKNOWN'if the system can't tell.UNFORMATTED=unf
- unf is a character variable that is assigned the value
'YES'if the file could be connected for unformatted I/O,'NO'if the file could not be connected for unformatted I/O, and'UNKNOWN'if the system cannot tell.UNIT=u
- u is an integer expression or * with the value of the unit. Exactly one of
FILEorUNITmust be used.Examples
Example 1: Inquire by unit:
LOGICAL OKINQUIRE( UNIT=3, OPENED=OK )IF ( OK ) CALL GETSTD ( 3, STDS )Example 2: Inquire by file:
LOGICAL THEREINQUIRE( FILE='.profile', EXIST=THERE )IF ( THERE ) CALL GETPROFILE( FC, PROFILE )Example 3: More than one answer, omitting the
UNIT=:
CHARACTER FN*32LOGICAL HASNAME, OKINQUIRE ( 3, OPENED=OK, NAMED=HASNAME, NAME=FN )IF ( OK .AND. HASNAME ) PRINT *, 'Filename="', FN, '"'
INTEGERThe
INTEGERstatement specifies the type to be integer for a symbolic constant, variable, array, function, or dummy function.Optionally, it specifies array dimensions and size and initializes with values.
INTEGER [*len[,]]v[*len[/c/]] [,v[*len[/c/]]...
Description
The declarations can be:
INTEGER,INTEGER*2,INTEGER*4,INTEGER*8.
INTEGERFor a declaration such as
INTEGER H, the variableHis usually oneINTEGER*4element in memory, interpreted as a single integer number. Specifying the size is nonstandard.![]()
If you do not specify the size, a default size is used. The default size, for a declaration such as
INTEGER H, can be altered by compiling with any of the options-dbl,-i2,-r8, or-xtypemap. See the discussion in Chapter 2 for details.
INTEGER*2![]()
For a declaration such as
INTEGER*2 H, the variableHis always anINTEGER*2element in memory, interpreted as a single integer number.
INTEGER*4![]()
For a declaration such as
INTEGER*4 H, the variableHis always anINTEGER*4element in memory, interpreted as a single integer number.
INTEGER*8![]()
For a declaration such as
INTEGER*8 H, the variableHis always anINTEGER*8element in memory, interpreted as a single integer number.Restrictions
Do not use
INTEGER*8variables or 8-byte constants or expressions when indexing arrays, otherwise, only 4 low-order bytes are taken into account. This action can cause unpredictable results in your program if the index value exceeds the range for 4-byte integers.Examples
Example 1: Each of these integer declarations are equivalent:
INTEGER U, V(9)INTEGER*4 U, V(9)INTEGER U*4, V(9)*4Example 2: Initialize:
INTEGER U / 1 /, V / 4 /, W*2 / 1 /, X*2 / 4 /
INTRINSICThe
INTRINSICstatement lists intrinsic functions that can be passed as actual arguments.
INTRINSICfun[,fun]...
Parameter Description fun Function name
Description
If the name of an intrinsic function is used as an actual argument, it must appear in an
INTRINSICstatement in the same program unit.Example: Intrinsic functions passed as actual arguments:
INTRINSIC SIN, COSX = CALC ( SIN, COS )Restrictions
A symbolic name must not appear in both an
EXTERNALand anINTRINSICstatement in the same program unit.The actual argument must be a specific name. Most generic names are also specific, but a few are not:
IMAG,LOG, andLOG10.A symbolic name can appear more than once in an
INTRINSICstatement.In the FORTRAN 77 Standard, a symbolic name can appear only once in anINTRINSICstatement.![]()
Because they are inline or generic, the following intrinsics cannot be passed as actual arguments:
LOGICALThe
LOGICALstatement specifies the type to be logical for a symbolic constant, variable, array, function, or dummy function.Optionally, it specifies array dimensions and initializes with values.
LOGICAL [*len[,]]v[*len[/c/]] [,v[*len[/c/]]...
Description
The declarations can be:
LOGICAL,LOGICAL*1,LOGICAL*2,LOGICAL*4,LOGICAL*8.
LOGICALFor a declaration such as
LOGICAL H, the variableHis usually oneINTEGER*4element in memory, interpreted as a single logical value. Specifying the size is nonstandard.![]()
If you do not specify the size, a default size is used. The default size, for a declaration such as
LOGICAL Z, can be altered by compiling with any of the options-dbl,-i2,-r8, or-xtypemap. See the discussion in Chapter 2 for details.
LOGICAL*1![]()
For a declaration such as
LOGICAL*1 H, the variableHis always anBYTEelement in memory, interpreted as a single logical value.
LOGICAL*2![]()
For a declaration such as
LOGICAL*2 H, the variableHis always anINTEGER*2element in memory, interpreted as a single logical value.
LOGICAL*4![]()
For a declaration such as
LOGICAL*4 H, the variableHis always anINTEGER*4element in memory, interpreted as a single logical value.
LOGICAL*8![]()
For a declaration such as
LOGICAL*8 H, the variableHis always anINTEGER*8element in memory, interpreted as a single logical value.Examples
Example 1: Each of these declarations are equivalent:
LOGICAL U, V(9)LOGICAL*4 U, V(9)LOGICAL U*4, V(9)*4Example 2: Initialize:
LOGICAL U /.false./, V /0/, W*4 /.true./, X*4 /'z'/
MAPThe
MAPdeclaration defines alternate groups of fields in a union.
MAPfield-declaration...[field-declaration]END MAPDescription
Each field declaration can be one of the following:
- Type declaration, which can include initial values
- Substructure--either another structure declaration, or a record that has been previously defined
- Union declaration--see UNION and MAP for more information.
Example
Example:
MAP:
STRUCTURE /STUDENT/CHARACTER*32 NAMEINTEGER*2 CLASSUNIONMAPCHARACTER*16 MAJOREND MAPMAPINTEGER*2 CREDITSCHARACTER*8 GRAD_DATEEND MAPEND UNIONEND STRUCTURE
NAMELISTThe
NAMELISTstatement defines a list of variables or array names, and associates it with a unique group name.
NAMELIST /grname/namelist[[,] /grname/namelist]...
Parameter Description grname Symbolic name of the group namelist List of variables and arrays
Description
The
NAMELISTstatement contains a group name and other items.Group Name
The group name is used in the namelist-directed I/O statement to identify the list of variables or arrays that are to be read or written. This name is used by namelist-directed I/O statements instead of an input/output list. The group name must be unique, and identifies a list whose items can be read or written.
A group of variables can be defined through several
NAMELISTstatements with the same group name. Together, these definitions are taken as defining oneNAMELISTgroup.Namelist Items
The namelist items can be of any data type. The items in the namelist can be variables or arrays, and can appear in more than one namelist. Only the items specified in the namelist can be read or written in namelist-directed I/O, but it is not necessary to specify data in the input record for every item of the namelist.
The order of the items in the namelist controls the order in which the values are written in namelist-directed output. The items in the input record can be in any order.
Restrictions
Input data can assign values to the elements of arrays or to substrings of strings that appear in a namelist.
The following constructs cannot appear in a
NAMELISTstatement:
- Constants (parameters)
- Array elements
- Records and record fields
- Character substrings
- Dummy assumed-size arrays
Example
Example: The
NAMELISTstatement:
CHARACTER*16 SAMPLELOGICAL*4 NEWREAL*4 DELTANAMELIST /CASE/ SAMPLE, NEW, DELTAIn this example, the group
CASEhas three variables:SAMPLE,NEW, andDELTA.
OPENThe
OPENstatement can connect an existing external file to a unit, create a file and connect it to a unit, or change some specifiers of the connection.
OPEN ([UNIT=]u, slist)
Description
The
OPENstatement determines the type of file named, whether the connection specified is legal for the file type (for instance,DIRECTaccess is illegal for tape andttydevices), and allocates buffers for the connection if the file is on tape or if the subparameterFILEOPT= 'BUFFER= n' is specified. Existing files are never truncated on opening.
Note For tape I/O, use theTOPEN()routines.
The following table summarizes the
OPENspecifiers:
The keywords can be specified in any order.
OPENSpecifier KeywordsThe following provides a detailed list of the
OPENspecifier keywords:[UNIT=] u
- u is an integer expression or an asterisk (*) that specifies the unit number. u is required. If u is first in the parameter list, then
UNIT=can be omitted.FILE=fin
- fin is a character expression naming the file to open. An
OPENstatement need not specify a file name. If the file name is not specified, a default name is created.- Reopening files: If you open a unit that is already open without specifying a file name (or with the previous file name), FORTRAN thinks you are reopening the file to change parameters. The file position is not changed. The only parameters you are allowed to change are
BLANK(NULLorZERO) andFORM(FORMATTEDor- Switching Files: If you open a unit that is already open, but you specify a different file name, it is as if you closed with the old file name before the open.
- Switching Units: If you open a file that is already open, but you specify a different unit, that is an error. This error is not detected by the
ERR=option, however, and the program does not terminate abnormally.- Scratch Files: If a file is opened with
STATUS='SCRATCH', a temporary file is created and opened. SeeSTATUS=sta.ACCESS=acc
- The
ACCESS=acc clause is optional. acc is a character expression. Possible values are:APPEND,DIRECT, orSEQUENTIAL. The default isSEQUENTIAL.- If
ACCESS='APPEND',SEQUENTIALandFILEOPT='EOF'are assumed. This is for opening a file to append records to an existing sequential-access file. OnlyWRITEoperations are allowed, although no error message is issued. This is an extension and can be applied only to disk files.- If
ACCESS='DIRECT',RECLmust also be given, since all I/O transfers are done in multiples of fixed-size records.- Only directly accessible files are allowed; thus, tty, pipes, and magnetic tape are not allowed. If you build a file as sequential, then you cannot access it as direct.
- If
FORMis not specified, unformatted transfer is assumed.- If
FORM='UNFORMATTED', the size of each transfer depends upon the data transferred.- If
ACCESS='SEQUENTIAL',RECLis ignored.The FORTRAN 77 Standard prohibits
RECLfor sequential access.- No padding of records is done.
- If you build a file as direct, then you cannot access it as sequential.
- Files do not have to be randomly accessible, in the sense that tty, pipes, and tapes can be used. For tapes, we recommend the
TOPEN()routines because they are more reliable.- If
FORMis not , formatted transfer is assumed.- If
FORM='FORMATTED', each record is terminated with a newline (\n) character; that is, each record actually has one extra character.- If
FORM='PRINT', the file acts like aFORM='FORMATTED'file, except for interpretation of the column-1 characters on the output (blank = single space, 0 = double space, 1 = form feed, and + = no advance).- If
FORM='UNFORMATTED', each record is preceded and terminated with anINTEGER*4count, making each record 8 characters longer than normal. This convention is not shared with other languages, so it is useful only for communicating between FORTRAN programs.FORM=fm
- The
FORM=fm clause is optional. fm is a character expression. Possible values are'FORMATTED','UNFORMATTED','BINARY'or'PRINT'.The default is
'FORMATTED'.- This option interacts with
ACCESS.'PRINT'makes it a print file.'BINARY'treats the file as a sequential unformatted file with no record marks.Specifying
ACCESS='DIRECT'orRECL=n withFORM='BINARY'generates an error. EachWRITEstatement writes as many bytes in binary as there are in the data on the output list. A READ statement reads as many bytes from the input file as are required by the input list. Since no record marks are recognized, it is not possible to read "outside the record". Other than abnormal system errors, the only input error that can occur is reading the end-of-file.BACKSPACEon aFORM='BINARY'file is not allowed and generates a runtime error.RECL=rl
- The
RECL=rl clause is required ifACCESS='DIRECT'and ignored otherwise.- rl is an integer expression for the length in characters of each record of a file. rl must be positive.
- If the record length is unknown, you can use
RECL=1; see Direct Access I/O for more information.- If
-xl[d]is not set, rl is number of characters, and record length is rl.- If
-xl[d]is set, rl is number of words, and record length is rl*4.- There are more details in the
ACCESS='SEQUENTIAL'section, above.- Each
WRITEdefines one record and eachREADreads one record (unread characters are flushed).- The default buffer size for tape is 64K characters. For tapes, we recommend the
TOPEN()routines because they are more reliable.ERR=s
- The
ERR=s clause is optional. s is a statement label of a statement to branch to if an error occurs during execution of theOPENstatement.IOSTAT=ios
- The
IOSTAT=ios clause is optional. ios is an integer variable that receives the error status from anOPEN. After the execution of theOPEN, if no error condition exists, then ios is zero; otherwise, it is some positive number.- If you want to avoid aborting the program when an error occurs on an
OPEN, includeERR=s orIOSTAT=ios.BLANK=blnk
- The
BLANK=blnk clause is optional, and is for formatted input only. The blnk is a character expression that indicates how blanks are treated. Possible values are'ZERO'and'NULL'.'ZERO'--Blanks are treated as zeroes.'NULL'--Blanks are ignored during numeric conversion. This is the default.STATUS=sta
- The
STATUS=sta clause is optional. sta is a character expression. Possible values are:'OLD','NEW','UNKNOWN', or'SCRATCH'.'OLD'-- The file already exists (nonexistence is an error). For example:STATUS='OLD'.'NEW'-- The file doesn't exist (existence is an error). If'FILE=name'is not specified, then a file named'fort.n'is opened, where n is the specified logical unit.'UNKNOWN'-- Existence is unknown. This is the default.'SCRATCH'-- For a file opened withSTATUS='SCRATCH', a temporary file with a name of the formtmp.FAAAxnnnnn is opened. Any otherSTATUSspecifier without an associated file name results in opening a file named'fort.n', where n is the specified logical unit number. By default, a scratch file is deleted when closed or during normal termination. If the program aborts, then the file may not be deleted. To prevent deletion,CLOSEwithSTATUS='KEEP'.- The FORTRAN 77 Standard prohibits opening a named file as scratch: if
OPENhas aFILE=name option, then it cannot have aSTATUS='SCRATCH'option. This FORTRAN extends the standard by allowing opening named files as scratch.Such files are normally deleted when closed or at normal termination.
TMPDIR: FORTRAN programs normally put scratch files in the current working directory. If theTMPDIRenvironment variable is set to a writable directory, then the program puts scratch files there.FILEOPT=fopt
![]()
- The
FILEOPT=fopt clause is optional. fopt is a character expression. Possible values are 'NOPAD','BUFFER=n', and'EOF'.'NOPAD'--Do not extend records with blanks if you read past the end-of-record (formatted input only). That is, a short record causes an abort with an error message, rather than just filling with trailing blanks and continuing.'BUFFER=n'-- Sets the buffer size to be used by the I/O unit to n bytes. This suboption is intended for use with regular files, such as disk files. For good performance, the buffer size should e a multiple of the page size. Using large buffers generally improves the performance of sequential I/O. Performance of direct I/O is usually best if the buffer size equals the record length. One exception is that if the record length is one, the buffer size should be at least one page.
Normally the BUFFER suboption should not be used with tape files, where the proper buffer size is determined by the tape hardware, the controllers, and the file system. Some kinds of tape drives offer limited functionality. These limitations can cause normal Fortran I/O to be unreliable. The tape I/O routines in the Fortran library (seetopen(3F)) are recommended alternatives for such drives.'EOF'--Opens a file at end-of-file rather than at the beginning (useful for appending data to file), for example,FILEOPT='EOF'. UnlikeACCESS='APPEND', in this case, bothREADandBACKSPACEare allowed.READONLY
![]()
- The file is opened read-only.
ACTION=act
- This specifier denotes file permissions. Possible values are:
READ,WRITE, andREADWRITE.- If act is
READ, it specifies that the file is opened read-only.- If act is
WRITE, it specifies that the file is opened write-only. You cannot execute aBACKSPACEstatement on a write-only file.- If act is
READWRITE, it specifies that the file is opened with both read and write permissions.Examples
Example 1: Open a file and connect it to unit 8--either of the following forms of the
OPENstatement opens the file,projectA/data.test, and connects it to FORTRAN unit 8:
OPEN(UNIT=8, FILE='projectA/data.test')OPEN(8, FILE='projectA/data.test')In the above example, these properties are established by default: sequential access, formatted file, and (unwisely) no allowance for error during file open.
Example 2: Explicitly specify properties:
OPEN(UNIT=8, FILE='projectA/data.test', & ACCESS='SEQUENTIAL', FORM='FORMATTED')Example 3: Either of these opens file,
fort.8, and connects it to unit 8:
OPEN(UNIT=8)OPEN(8)In the above example, you get sequential access, formatted file, and no allowance for error during file open. If the file,
fort.8does not exist before execution, it is created. The file remains after termination.Example 4: Allowing for open errors:
OPEN(UNIT=8, FILE='projectA/data.test', ERR=99)The above statement branches to
99if an error occurs duringOPEN.Example 5: Allowing for variable-length records;
OPEN(1, ACCESS='DIRECT', recl=1)See Direct Access I/O for more information about variable-length records.
Example 6: Scratch file:
OPEN(1, STATUS='SCRATCH')This statement opens a temporary file with a name, such as
tmp.FAAAa003zU.The file is usually in the current working directory, or inTMPDIRif that environment variable is set.
OPTIONSThe
OPTIONSstatement overrides compiler command-line options.
OPTIONS/qualifier[/qualifier...]Description
The following table shows the
OPTIONSstatement qualifiers:
Restrictions
The
OPTIONSstatement must be the first statement in a program unit; it must be before theBLOCK DATA,FUNCTION,PROGRAM, andSUBROUTINEstatements.Options set by the
OPTIONSstatement override those of the command line.Options set by the
OPTIONSstatement endure for that program unit only.A qualifier can be abbreviated to four or more characters.
Uppercase or lowercase is not significant.
Example
For the following source, integer variables declared with no explicit size occupy 4 bytes rather than 2, with or without the
-i2option on the command line. This rule does not change the size of integer constants, only variables.
OPTIONS /I4PROGRAM FFT...ENDBy way of contrast, if you use
/NOI4, then all integer variables declared with no explicit size occupy 2 bytes rather than 4, with or without the-i2option on the command line. However, integer constants occupy 2 bytes with-i2, and 4 bytes otherwise.
PARAMETERThe
PARAMETERstatement assigns a symbolic name to a constant.
PARAMETER (p=e[,p=e] ... )
Parameter Description p Symbolic name e Constant expression
An alternate syntax is allowed, if the
-xlflag is set:![]()
In this alternate form, the type of the constant expression determines the type of the name; no conversion is done.
Description
e can be of any type and the type of symbolic name and the corresponding expression must match.
A symbolic name can be used to represent the real part, imaginary part, or both parts of a complex constant.
A constant expression is made up of explicit constants and parameters and the FORTRAN operators. See Constant Expressions for more information.
No structured records or record fields are allowed in a constant expression.
Exponentiation to a floating-point power is not allowed, and a warning is issued.
If the type of the data expression does not match the type of the symbolic name, then the type of the name must be specified by a type statement or
IMPLICITstatement prior to its first appearance in aPARAMETERstatement, otherwise conversion will be performed.If a
CHARACTERstatement explicitly specifies the length for a symbolic name, then the constant in thePARAMETERstatement can be no longer than that length. Longer constants are truncated, and a warning is issued. TheCHARACTERstatement must appear before thePARAMETERstatement.If a
CHARACTERstatement uses*(*)to specify the length for a symbolic name, then the data in thePARAMETERstatement are used to determine the length of the symbolic constant. TheCHARACTERstatement must appear before thePARAMETERstatement.Any symbolic name of a constant that appears in an expression e must have been defined previously in the same or a different
PARAMETERstatement in the same program unit.
The Sun WorkShop FORTRAN 77 compiler extends the PARAMETER statement to accept any expression, including non-constant expressions. The statement will get a warning message to indicate that it is non-standard, and the value will be determined at runtime wherever the symbol is referenced. However, if the symbol defined in a PARAMETER statement with a non-constant expression appears in a statement where a constant is expected (such as a DATA statement) it will get an error.
Restrictions
A symbolic constant must not be defined more than once in a program unit.
If a symbolic name appears in a
PARAMETERstatement, then it cannot represent anything else in that program unit.A symbolic name cannot be used in a constant format specification, but it can be used in a variable format specification.
If you pass a parameter as an argument, and the subprogram tries to change it, you may get a runtime error.
Examples
Example 1: Some real, character, and logical parameters:
CHARACTER HEADING*10LOGICAL TPARAMETER (EPSILON=1.0E-6, PI=3.141593,& HEADING=' IO Error #',& T=.TRUE.)...Example 2: Let the compiler count the characters:
CHARACTER HEADING*(*)PARAMETER (HEADING='I/O Error Number')...Example 3: The alternate syntax, if the
-xlcompilation flag is specified:
PARAMETER FLAG1 = .TRUE.The above statement is treated as:
LOGICAL FLAG1PARAMETER (FLAG1 = .TRUE.)An ambiguous statement that could be interpreted as either a
PARAMETERstatement or an assignment statement is always taken to be the former, as long as either the-xlor-xldoption is specified.Example: An ambiguous statement:
PARAMETER S = .TRUE.With
-xl, the above statement is aPARAMETERstatement about the variableS.
PARAMETER S = .TRUE.It is not an assignment statement about the variable
PARAMETERS.
PARAMETERS = .TRUE.
PAUSEThe
PAUSEstatement suspends execution, and waits for you to type:go.
PAUSE[str]
Parameter Description str String of not more than 5 digits or a character constant
Description
The
PAUSEstatement suspends program execution temporarily, and waits for acknowledgment. On acknowledgment, execution continues.If the argument string is present, it is displayed on the screen (written to
stdout), followed by the following message:
PAUSE. To resume execution, type: goAny other input will terminate the program.After you type:
go, execution continues as if aCONTINUEstatement is executed. See this example:
If
stdinis not attyI/O device,PAUSEdisplays a message like this:
PAUSE: To resume execution, type: kill -15pidExample:
stdinnot attyI/O device:
demo%a.out < mydatafilePAUSE: To resume execution, type: kill -15 20537demo%For the above example, type the following command line at a shell prompt in some other window. The window displaying the message cannot accept command input.
demo%kill -15 20537
POINTERThe
POINTERstatement establishes pairs of variables and pointers.
POINTER (p1,v1) [, (p2,v2) ... ]
Parameter Description v1, v2 Pointer-based variables, also called pointees p1, p2 Corresponding pointers
Description
Each pointer contains the address of its paired variable.
A pointer-based variable, or pointee, is a variable paired with a pointer in a
POINTERstatement. A pointer-based variable is usually called just a based variable. The pointer is the integer variable that contains the address. (Variable names appearing onPOINTERstatements are consideredVOLATILEby the compiler.)The use of pointers is described in Pointers.
Examples
Example 1: A simple POINTER statement:
POINTER (P, V)Here,
Vis a pointer-based variable, andPis its associated pointer.Example 2: Using the
LOC()function to get an address:
* ptr1.f: Assign an address via LOC()POINTER (P, V)CHARACTER A*12, V*12DATA A / 'ABCDEFGHIJKL' /P = LOC(A)PRINT *, V(5:5)ENDIn the above example, the
CHARACTERstatement allocates 12 bytes of storage forA, but no storage forV; it merely specifies the type ofVbecauseVis a pointer-based variable. You then assign the address ofAtoP, so now any use ofVrefers toAby the pointerP. The program prints anE.Example 3: Memory allocation for pointers, by
:MALLOC
POINTER (P1, X), (P2, Y), (P3, Z)...P1 = MALLOC (36)...CALL FREE (P1)...In the above example, you get 36 bytes of memory from
MALLOC()and then, after some other instructions, probably using that chunk of memory, tellFREE()to return those same 36 bytes to the memory manager.Example 4: Get the area of memory and its address
:
POINTER (P, V)CHARACTER V*12, Z*1P = MALLOC(12)...ENDIn the above example, you obtain 12 bytes of memory from the function
MALLOC()and assign the address of that block of memory to the pointerP.Example 5: Dynamic allocation of arrays:
This is a slightly more realistic example. The size might well be some large number, say, 10,000. Once that's allocated, the subroutines perform their tasks, not knowing that the array was dynamically allocated.
Example 6: One way to use pointers to make a linked list in
f77:
demo%f77 -silent Linked.f"Linked.f", line 6: Warning: local variable "b" never used"Linked.f", line 31: Warning: local variable "b" never useddemo%a.out1 aaa2 bbb3 ccc4 ddddemo%
- Do not optimize programs using pointers like this with
-O3,-O4,or-O5.- The warnings can be ignored.
- This is not the normal usage of pointers described at the start of this section.
The
stdout.
Parameter Description f Format identifier iolist List of variables, substrings, arrays, and records grname Name of the namelist group
Description
The
Format Identifier
f is a format identifier and can be:
- An asterisk (
*), which indicates list-directed I/O. See List-Directed I/O on for more information.- The label of a
FORMATstatement that appears in the same program unit.- An integer variable name that has been assigned the label of a
FORMATstatement that appears in the same program unit.- A character expression or integer array that specifies the format string. The integer array is nonstandard.
![]()
Output List
iolist can be empty or can contain output items or implied
DOlists. The output items must be one of the following:
- Variables
- Substrings
- Arrays
- Array elements
- Record fields
- Any other expression
A simple unsubscripted array name specifies all of the elements of the array in memory storage order, with the leftmost subscript increasing more rapidly.
Implied DO lists are described on Implied DO Lists.
Namelist-Directed
The second form of the
NAMELISTstatement.Execution proceeds as follows:
1. The format, if specified, is established.2. If the output list is not empty, data is transferred from the list to standard output.
- If a format is specified, data is edited accordingly.
3. In the second form of theRestrictions
Output from an exception handler is unpredictable. If you make your own exception handler, do not do any FORTRAN output from it. If you must do some, then call abort right after the output. Doing so reduces the relative risk of a program freeze. FORTRAN I/O from an exception handler amounts to recursive I/O. See the next point.
Recursive I/O does not work reliably. If you list a function in an I/O list, and if that function does I/O, then during runtime, the execution may freeze, or some other unpredictable problem may occur. This risk exists independent of parallelization.
Example: Recursive I/O fails intermittently:
PRINT *, x, f(x) Not allowed because f() does I/O.ENDFUNCTION F(X)PRINT *, XRETURNENDExamples
Example 1: Formatted scalars:
CHARACTER TEXT*16PRINT 1, NODE, TEXT1 FORMAT (I2, A16)Example 2: List-directed array:
PRINT *, I, J, (VECTOR(I), I = 1, 5)Example 3: Formatted array:
INTEGER VECTOR(10)PRINT '(12 I2)', I, J, VECTORExample 4: Namelist:
CHARACTER LABEL*16REAL QUANTITYINTEGER NODENAMELIST /SUMMARY/ LABEL, QUANTITY, NODEPRINT SUMMARY
PROGRAMThe
PROGRAMstatement identifies the program unit as a main program.
PROGRAMpgm
Parameter Description pgm Symbolic name of the main program
Description
For the loader, the main program is always named
MAIN. ThePROGRAMstatement serves only the person who reads the program.Restrictions
The
PROGRAMstatement can appear only as the first statement of the main program.The name of the program cannot be:
- The same as that of an external procedure or common block
MAIN(all uppercase), or a runtime error resultsThe name of the program can be the same as a local name in the main program.
The FORTRAN 77 Standard does not allow this practice.
Example
Example: A
PROGRAMstatement:
PROGRAM US_ECONOMYNVARS = 2NEQS = 2...
READThe
READstatement reads data from a file or the keyboard to items in the list.
Note Use theTOPEN()routines to read from tape devices. See the Fortran Library Reference Manual.
READ([UNIT=]u[,[FMT=]f][, IOSTAT=ios][, REC=rn][, END=s][,ERR=s])iolist
READ([UNIT=]u,[NML=]grname[, IOSTAT=ios][, END=s][, ERR=s])
READgrname
An alternate to the
UNIT=u,REC=rn form is as follows:![]()
The options can be specified in any order.
Description
The
READstatement accepts the following arguments.Unit Identifier
u is either an external unit identifier or an internal file identifier.
An external unit identifier must be one of these:
- A nonnegative integer expression
- An asterisk (
*), identifying stdin, normally connected to the keyboardIf the optional characters
UNIT=are omitted from the unit specifier, then u must be the first item in the list of specifiers.Format Identifier
f is a format identifier and can be:
- An asterisk (
*), indicating list-directed I/O. See List-Directed I/O for more information.- A label of a
FORMATstatement that appears in the same program unit- An integer variable name that has been assigned the label of a
FORMATstatement that appears in the same program unit- A character expression or integer array specifying the format string. This is called a runtime format or a variable format. The integer array is nonstandard.
![]()
See Runtime Formats for details on formats evaluated at runtime.
If the optional characters,
FMT=, are omitted from the format specifier, then f must appear as the second argument for a formatted read; otherwise, it must not appear at all.Unformatted data transfer from internal files and terminal files is not allowed, hence, f must be present for such files.
List-directed data transfer from direct-access and internal files is allowed; hence, f can be an asterisk for such files.
![]()
If a file is connected for formatted I/O, unformatted data transfer is not allowed, and vice versa.
I/O Status Specifier
ios must be an integer variable or an integer array element.
Record Number
rn must be a positive integer expression, and can be used for direct-access files only. rn can be specified for internal files.
![]()
End-of-File Specifier
s must be the label of an executable statement in the same program unit in which the
READstatement occurs.The
END=s andREC=rn specifiers can be present in the sameREADstatement.![]()
Error Specifier
s must be the label of an executable statement in the same program unit in which the
READstatement occurs.Input List
iolist can be empty or can contain input items or implied
DOlists. The input items can be any of the following:
- Variables
- Substrings
- Arrays
- Array elements
- Record fields
A simple unsubscripted array name specifies all of the elements of the array in memory storage order, with the leftmost subscript increasing more rapidly.
Implied DO lists are described on Implied DO Lists.
Namelist-Directed
READThe third and fourth forms of the
READstatement are used to read the items of the specified namelist group, and grname is the name of the group of variables previously defined in aNAMELISTstatement.Execution
Execution proceeds as follows:
1. The file associated with the specified unit is determined.
- The format, if specified, is established. The file is positioned appropriately prior to the data transfer.
2. If the input list is not empty, data is transferred from the file to the corresponding items in the list.
- The items are processed in order as long as the input list is not exhausted. The next specified item is determined and the value read is transmitted to it. Data editing in formatted
READis done according to the specified format.3. In the third and fourth forms of namelist-directedREAD, the items of the specified namelist group are processed according to the rules ofnamelist-directed input.4. The file is repositioned appropriately after data transfer.5. If ios is specified and no error occurred, it is set to zero.
- ios is set to a positive value, if an error or end of file was encountered.
6. If s is specified and end of file was encountered, control is transferred to s.7. If s is specified and an error occurs, control is transferred to s.The above two forms operate the same way as the others, except that reading from the keyboard is implied.
Execution has the following differences:
- When the input list is exhausted, the cursor is moved to the start of the line following the input. For an empty input list, the cursor is moved to the start of the line following the input.
- If an end-of-line,
CR, orNLis reached before the input list is satisfied, input continues from the next line.- If an end-of-file (Control-D) is received before the input list is satisfied, input stops, and unsatisfied items of the input list remain unchanged.
If u specifies an external unit that is not connected to a file, an implicit
OPENoperation is performed equivalent to opening the file with the options in the following example:
OPEN(u, FILE='FORT.u', STATUS='OLD', ACCESS='SEQUENTIAL',& FORM=fmt)
- The value of fmt is
'FORMATTED'or'UNFORMATTED'accordingly, as the read is formatted or unformatted.- A simple unsubscripted array name specifies all of the elements of the array in memory storage order, with the leftmost subscript increasing more rapidly.
- An attempt to read the record of a direct-access file that has not been written, causes all items in the input list to become undefined.
- The record number count starts from one.
- Namelist-directed input is permitted on sequential access files only.
Examples
Example 1: Formatted read, trap I/O errors, EOF, and I/O status:
READ( 1, 2, ERR=8, END=9, IOSTAT=N ) X, Y...8 WRITE( *, * ) 'I/O error # ', N, ', on 1'STOP9 WRITE( *, * ) 'EoF on 1'RETURNENDExample 2: Direct, unformatted read, trap I/O errors, and I/O status:
READ( 1, REC=3, IOSTAT=N, ERR=8 ) V...4 CONTINUERETURN8 WRITE( *, * ) 'I/O error # ', N, ', on 1'ENDExample 3: List-directed read from keyboard:
READ(*,*)A,VorREAD*, A, VExample 4: Formatted read from an internal file:
CHARACTER CA*16 / 'abcdefghijklmnop' /, L*8, R*8READ( CA, 1 ) L, R1 FORMAT( 2 A8 )Example 5: Read an entire array:
DIMENSION V(5)READ( 3, '(5F4.1)') VExample 6: Namelist-directed read:
CHARACTERSAMPLE*16LOGICALNEW*4REALDELTA*4NAMELIST/G/SAMPLE,NEW,DELTA...READ(1,G)orREAD(UNIT=1,NML=G)orREAD(1,NML=G)
REALThe
REALstatement specifies the type of a symbolic constant, variable, array, function, or dummy function to be real, and optionally specifies array dimensions and size, and initializes with values.
REAL [*len[,]]v[*len[/c/]] [,v[*len[/c/]]...
Description
Following are descriptions for
REAL,REAL*4,REAL*8, andREAL*16.
REALFor a declaration such as
REAL W, the variableWis usually aREAL*4element in memory, interpreted as a real number. Specifying the size is nonstandard.![]()
The default size, for a declaration such as
REAL H, can be altered by compiling with any of the options-dbl,-r8, or-xtypemap. See the discussion in Chapter 2 for details.
REAL*4![]()
For a declaration such as
REAL*4 W, the variableWis always aREAL*4element in memory, interpreted as a single-width real number.
REAL*8![]()
For a declaration such as
REAL*8 W, the variableWis always aREAL*8element in memory, interpreted as a double-width real number.
REAL*16![]()
(SPARC only) For a declaration such as
REAL*16 W, the variableWis always an element of typeREAL*16in memory, interpreted as a quadruple-width real.Examples
Example 1: Simple real variables--these declarations are all equivalent:
REAL U, V(9)REAL*4 U, V(9)REAL U*4, V(9)*4Example 2: Initialize variables (
REAL*16is SPARC only):
REAL U/ 1.0 /, V/ 4.3 /, D*8/ 1.0 /, Q*16/ 4.5 /Example 3: Specify dimensions for some real arrays:
REAL A(10,100), V(10)REAL X*4(10), Y(10)*4Example 4: Initialize some arrays:
REAL A(10,100) / 1000 * 0.0 /, B(2,2) /1.0, 2.0, 3.0, 4.0/Example 5: Double and quadruple precision (
REAL*16is SPARC only):
REAL*8 RREAL*16 QDOUBLE PRECISION DIn the above example,
DandRare both double precision;Qis quadruple precision.
RECORDThe
RECORDstatement defines variables to have a specified structure, or arrays to be arrays of variables with such structures.
RECORD /struct-name/record-list[,/struct-name/record-list]...
Parameter Description struct_name Name of a previously declared structure record_list List of variables, arrays, or array declarators
Description
A structure is a template for a record. The name of the structure is included in the
STRUCTUREstatement, and once a structure is thus defined and named, it can be used in aRECORDstatement.The record is a generalization of the variable or array: where a variable or array has a type, the record has a structure. Where all the elements of an array must be of the same type, the fields of a record can be of different types.
The
RECORDline is part of an inherently multiline group of statements, and neither theRECORDline nor theENDRECORDline has any indication of continuation. Do not put a nonblank in column six, nor an&in column one.Structures, fields, and records are discussed in Structures.
Restrictions
- Each record is allocated separately in memory.
- Initially, records have undefined values.
- Records, record fields, record arrays, and record-array elements are allowed as arguments and dummy arguments. When you pass records as arguments, their fields must match in type, order, and dimension. The record declarations in the calling and called procedures must match.
- Within a union declaration, the order of the map fields is not relevant.
- Record fields are not allowed in
COMMONstatements.- Records and record fields are not allowed in
DATA,EQUIVALENCE,NAMELIST,PARAMETER,AUTOMATIC,STATIC, orSAVEstatements. To initialize records and record fields, use theSTRUCTUREstatement. See STRUCTURE for more information.Example
Example 1: Declare some items to be records of a specified structure:
STRUCTURE /PRODUCT/INTEGER*4 IDCHARACTER*16 NAMECHARACTER*8 MODELREAL*4 COSTREAL*4 PRICEEND STRUCTURERECORD /PRODUCT/ CURRENT, PRIOR, NEXT, LINE(10)...Each of the three variables
CURRENT,PRIOR, andNEXTis a record which has thePRODUCTstructure, andLINEis an array of 10 such records.Example 2: Define some fields of records, then use them:
The above program produces the following output:
82CacheBoard1000.0096K
RETURNA
RETURNstatement returns control to the calling program unit.
RETURN[e]
Parameter Description e Expression of type INTEGERorREAL
Description
Execution of a
RETURNstatement terminates the reference of a function or subroutine.Execution of an
ENDstatement in a function or a subroutine is equivalent to the execution of aRETURNstatement.![]()
The expression e is evaluated and converted to integer, if required. e defines the ordinal number of the alternate return label to be used. Alternate return labels are specified as asterisks (or ampersands)
in the
SUBROUTINEstatement.If e is not specified, or the value of e is less than one or greater than the number of asterisks or ampersands in the
SUBROUTINEstatement that contains theRETURNstatement, control is returned normally to the statement following theCALLstatement that invoked the subroutine.If the value of e is between one and the number of asterisks (or ampersands) in the
SUBROUTINEstatement, control is returned to the statement identified by the eth alternate. ARETURNstatement can appear only in a function subprogram or subroutine.Examples
Example 1: Standard return:
CHARACTER*25 TEXTTEXT = "Some kind of minor catastrophe"...CALL OOPS ( TEXT )STOPENDSUBROUTINE OOPS ( S )CHARACTER S* 32WRITE (*,*) SRETURNENDExample 2: Alternate return:
REWINDThe
REWINDstatement positions the file associated with the specified unit to its initial point.
Note Use theTOPEN()routines to rewind tape devices. See the Fortran Library Reference for details.
REWIND ([UNIT=]u[, IOSTAT=ios] [, ERR=s])
Description
The options can be specified in any order.
Rewinding a unit not associated with any file has no effect. Likewise,
REWINDin a terminal file has no effect either.Using a
REWINDstatement on a direct-access file is not defined in the FORTRAN 77 Standard, and is unpredictable.Examples
Example 1: Simple form of unit specifier:
ENDFILE 3REWIND 3READ (3,'(I2)') IREWIND 3READ (3,'(I2)')IExample 2:
REWINDwith theUNIT=u form of unit specifier and error trap:
INTEGER CODE...REWIND (UNIT = 3)REWIND (UNIT = 3, IOSTAT = CODE, ERR = 100)...100 WRITE (*,*) 'error in rewinding'STOP
SAVEThe
SAVEstatement preserves items in a subprogram after theRETURNorENDstatements are executed, preventing them from becoming undefined.
SAVE [v[,v] ... ]
Parameter Description v Name of an array, variable, or common block (enclosed in slashes), occurring in a subprogram
Description
SAVEvariables are placed in an internal static area. All common blocks are already preserved because they have been allocated to a static area. Therefore, common block names specified inSAVEstatements are allowed but ignored.A
SAVEstatement is optional in the main program and has no effect.A
SAVEwith no list preserves all local variables and arrays in the routine.Local variables and arrays are already static by default, predisposing the need for
SAVE. However, usingSAVEcan ensure portability, especially with routines that leave a subprogram by some way other than aRETURN.Restrictions
The following constructs must not appear in a
SAVEstatement:
- Variables or arrays in a common block
- Dummy argument names
- Record names
- Procedure names
- Automatic variables or arrays
Example
Example: A
SAVEstatement:
SUBROUTINE FFA(N)DIMENSION A(1000,1000), V(1000)SAVE A...RETURNENDStatement Function
A statement function statement is a function-like declaration, made in a single statement.
fun
([d[,d]...]) =e
Parameter Description fun Name of statement function being defined d Statement function dummy argument e Expression. e can be any of the types arithmetic, logical, or character.
Description
If a statement function is referenced, the defined calculations are inserted.
Example: The following statement is a statement function:
ROOT( A, B, C ) = (-B + SQRT(B**2-4.0*A*C))/(2.0*A)The statement function argument list indicates the order, number, and type of arguments for the statement function.
A statement function is referenced by using its name, along with its arguments, as an operand in an expression.
Execution proceeds as follows:
1. If they are expressions, actual arguments are evaluated.2. Actual arguments are associated with corresponding dummy arguments.3. The expression e, the body of a statement function, is evaluated.4. If the type of the above result is different from the type of the function name, then the result is converted.5. Return the value.The resulting value is thus available to the expression that referenced the function.
Restrictions
- A statement function must appear only after the specification statements and before the first executable statement of the program unit in which it is referenced.
- A statement function is not executed at the point where it is specified. It is executed, as any other, by the execution of a function reference in an expression.
- The type conformance between fun and e are the same as those for the assignment statement. The type of fun and e can be different, in which case e is converted to the type of fun.
- The actual arguments must agree in order, number, and type with corresponding dummy arguments.
- If a dummy argument is defined as a structure, the corresponding actual argument must be similarly defined as the same structure.
- A dummy argument cannot be an array or function name, or have the same name as the function.
- The same argument cannot be specified more than once in the argument list.
- The statement function may be referenced only in the program unit that contains it.
- The name of a statement function cannot be an actual argument. Nor can it appear in an
EXTERNALstatement.- The type of the argument is determined as if the statement function were a whole program unit in itself.
- Even if the name of a statement function argument is the same as that of another local variable, the reference is considered a dummy argument of the statement function, not the local variable of the same name.
- The length specification of a character statement function or its dummy argument of type
CHARACTERmust be an integer constant expression.- A statement function cannot be invoked recursively.
Examples
Example 1: Arithmetic statement function:
PARAMETER ( PI=3.14159 )REAL RADIUS, VOLUMESPHERE ( R ) = 4.0 * PI * (R**3) / 3.0READ *, RADIUSVOLUME = SPHERE( RADIUS )...Example 2: Logical statement function:
LOGICAL OKFILEINTEGER STATUSOKFILE ( I ) = I .LT. 1READ( *, *, IOSTAT=STATUS ) X, YIF ( OK FILE(STATUS) ) CALL CALC ( X, Y, A )...Example 3: Character statement function:
CHARACTER FIRST*1, STR*16, S*1FIRST(S) = S(1:1)READ( *, * ) STRIF ( FIRST(STR) .LT. " " ) CALL CONTROL ( S, A )...
STATICThe
STATICstatement ensures that the specified items are stored in static memory.
STATIClist
Parameter Description list List of variables and arrays
Description
All local variables and arrays are classified static by default: there is exactly one copy of each datum, and its value is retained between calls. You can also explicitly define variables as static or automatic in a
STATICorAUTOMATICstatement, or in any type statement orIMPLICITstatement.However, you can still use
STATICto ensure portability, especially with routines that leave a subprogram by some way other than aRETURN.
- Arguments and function values are automatic.
- A
STATICstatement and a type statement cannot be combined to make aSTATICtype statement. For example, the statementSTATIC REAL Xdoes not declare the variableXto be bothSTATICandREAL; it declares the variableREALXto beSTATIC.Example
STATIC A, B, CREAL P, D, QSTATIC P, D, QIMPLICIT STATIC (X-Z)
STOPThe
STOPstatement terminates execution of the program.
STOP [str]
Parameter Description str String of no more that 5 digits or a character constant
Description
The argument str is displayed when the program stops.
If str is not specified, no message is displayed.
Examples
The above statement displays:
STOP: 9Example 2: Character:
stop 'error'The above statement displays:
STOP: error
STRUCTUREThe
STRUCTUREstatement organizes data into structures.
STRUCTURE [/structure-name/] [field-list]Each field declaration can be one of the following:
- A substructure--either another structure declaration, or a record that has been previously defined
- A union declaration
- A type declaration, which can include initial values
Description
A
STRUCTUREstatement defines a form for a record by specifying the name, type, size, and order of the fields that constitute the record. Optionally, it can specify the initial values.A structure is a template for a record. The name of the structure is included in the
STRUCTUREstatement, and once a structure is thus defined and named, it can be used in aRECORDstatement.The record is a generalization of the variable or array--where a variable or array has a type, the record has a structure. Where all the elements of an array must be of the same type, the fields of a record can be of different types.
Structures, fields, and records are described in Structures.
Restrictions
The name is enclosed in slashes and is optional in nested structures only.
If slashes are present, a name must be present.
You can specify the field-list within nested structures only.
There must be at least one field-declaration.
Each structure-name must be unique among structures, although you can use structure names for fields in other structures or as variable names.
The only statements allowed between the
STRUCTUREstatement and theENDSTRUCTUREstatement are field-declaration statements andPARAMETERstatements. APARAMETERstatement inside a structure declaration block is equivalent to one outside.Restrictions for Fields
Fields that are type declarations use the identical syntax of normal
FORTRAN type statements, and allf77types are allowed, subject to the following rules and restrictions:
- Any dimensioning needed must be in the type statement. The
DIMENSIONstatement has no effect on field names.- You can specify the pseudo-name
%FILLfor a field name. The%FILLis provided for compatibility with other versions of FORTRAN. It is not needed inf77because the alignment problems are taken care of for you. It is a useful feature if you want to make one or more fields not referenceable in some particular subroutine. The only thing that%FILLdoes is provide a field of the specified size and type, and preclude referencing it.- You must explicitly type all field names. The
IMPLICITstatement does not apply to statements in aSTRUCTUREdeclaration, nor do the implicitI,J,K,L,M,Nrules apply.- You cannot use arrays with adjustable or assumed size in field declarations, nor can you include passed-length
CHARACTERdeclarations.In a structure declaration, the offset of field n is the offset of the preceding field, plus the length of the preceding field, possibly corrected for any adjustments made to maintain alignment.
You can initialize a field that is a variable, array, substring, substructure, or union.
Examples
Example 1: A structure of five fields:
STRUCTURE /PRODUCT/INTEGER*4 ID / 99 /CHARACTER*16 NAMECHARACTER*8 MODEL / 'Z' /REAL*4 COSTREAL*4 PRICEEND STRUCTURERECORD /PRODUCT/ CURRENT, PRIOR, NEXT, LINE(10)In the above example, a structure named
PRODUCTis defined to consist of the fieldsID,NAME,MODEL,COST, andPRICE. Each of the three variables,CURRENT,PRIOR, andNEXT, is a record which has thePRODUCTstructure, andLINEis an array of 10 such records. Every such record has itsIDinitially set to 99, and itsMODELinitially set toZ.Example 2: A structure of two fields:
STRUCTURE /VARLENSTR/INTEGER*4 NBYTESCHARACTER A*25END STRUCTURERECORD /VARLENSTR/ VLSVLS.NBYTES = 0
SUBROUTINEThe
SUBROUTINEstatement identifies a named program unit as a subroutine, and specifies arguments for it.
SUBROUTINEsub[([d[,d]...])]
Parameter Description sub Name of subroutine subprogram d Variable name, array name, record name, or dummy procedure name, an asterisk, or an ampersand
Description
A subroutine subprogram must have a
SUBROUTINEstatement as the first statement. A subroutine can have any other statements, except aBLOCK DATA,FUNCTION,PROGRAM, or anotherSUBROUTINEstatement.sub is the name of a subroutine and is a global name, and must not be the same as any other global name such as a common block name or a function name. Nor can it be the same as any local name in the same subroutine.
d is the dummy argument, and multiple dummy arguments are separated by commas. d can be one of the following:
- Variable name
- Array name
- Dummy procedure name
- Record name
- Asterisk (
*) or an ampersand (&)![]()
The dummy arguments are local to the subroutine and must not appear in any of the following statements, except as a common block name:
EQUIVALENCEPARAMETERSAVESTATICAUTOMATICINTRINSICDATACOMMONThe actual arguments in the
CALLstatement that references a subroutine must agree with the corresponding formal arguments in theSUBROUTINEstatement, in order, number, and type. An asterisk (or an ampersand) in the formal argument list denotes an alternate return label. ARETURNstatement in this procedure can specify the ordinal number of the alternate return to be taken.Examples
Example 1: A variable and array as parameters:
SUBROUTINE SHR ( A, B )CHARACTER A*8REAL B(10,10)...RETURNENDExample 2: Standard alternate returns:
In this example, the
RETURN 1statement refers to the first alternate return label (first *). TheRETURN 2statement refers to the second alternate return label (second *) specified in theSUBROUTINEstatement.
TYPEThe
TYPEstatement writes to
stdout.
TYPEgrname
Parameter Description f Format identifier iolist List of variables, substrings, arrays, and records grname Name of the namelist group
Description
The
TYPEstatement is provided for compatibility and is equivalent to:
WRITE(*,f)[ iolist ]WRITE(*,grname)Example
Example: Formatted and namelist output:
INTEGER V(5)REAL X(9), YNAMELIST /GNAM/ X, Y...TYPE 1, V1 FORMAT( 5 I3 )...TYPE GNAM...The Type Statement
The type statement specifies the data type of items in the list, optionally specifies array dimensions, and initializes with values.
type
v[/clist/] [,v[/clist/]...
type can be preceded by either
AUTOMATICorSTATIC.Description
A type statement can be used to:
- Confirm or to override the type established by default or by the
IMPLICITstatement- Specify dimension information for an array, or confirm the type of an intrinsic function
- Override the length by one of the acceptable lengths for that data type
A type statement can assign initial values to variables, arrays, or record fields by specifying a list of constants (clist) as in a
DATAstatement.![]()
The general form of a type statement is:
type VariableName
/constant/ ...type
ArrayName/constant,... /Example: Various type statements:
CHARACTER LABEL*12 / 'Standard' /COMPLEX STRESSPT / ( 0.0, 1.0 ) /INTEGER COUNT / 99 /, Z / 1 /REAL PRICE / 0.0 /, COST / 0.0 /REAL LIST(8) / 0.0, 6*1.0, 0.0 /When you initialize a data type, remember the following restrictions:
- For a simple variable, there must be exactly one constant.
- If any element of an array is initialized, all must be initialized.
- You can use an integer as a repeat factor, followed by an asterisk (
*), followed by a constant. In the example above, six values of 1.0 are stored into array elements 2, 3, 4, 5, 6, and 7 ofLIST.- If a variable or array is declared
AUTOMATIC, then it cannot be initialized.- A pointer-based variable or array cannot be initialized. For example:
INTEGER Z / 4 /POINTER ( x, Z ) Warning issued, not initialized
- In this case, the compiler issues a warning message, and
Zis not initialized.- If a variable or array is not initialized, its values are undefined.
- If such initialization statements involve variables in
COMMON, and the-ansicompiler flag is set, then a warning is issued.
Note Compiling with any of the options-dbl,-r8,-i2, or-xtypemapcan alter the default size of names typed without an explicit size. See the discussion in Chapter 2.
Restrictions
A symbolic name can appear only once in type statements in a program unit.
A type statement must precede all executable statements.
Example
Example: The type statement:
INTEGER*2 I, J/0/REAL*4 PI/3.141592654/,ARRAY(10)/5*0.0,5*1.0/CHARACTER*10 NAMECHARACTER*10 TITLE/'Heading'/
Jis initialized to0PIis initialized to3.141592654- The first five elements of
ARRAYare initialized to 0.0- The second five elements of
ARRAYare initialized to 1.0TITLEis initialized to 'Heading'
UNIONandMAPThe
UNIONstatement defines groups of fields that share memory at runtime.
The syntax of a
UNIONdeclaration is as follows:
UNIONMAPfield-declarationfield-declaration...ENDMAPMAPfield-declarationfield-declaration...END MAPEND UNIONDescription
A
MAPstatement defines alternate groups of fields in a union. During execution, one map at a time is associated with a shared storage location. When you reference a field in a map, the fields in any previous map become undefined, and are succeeded by the fields in the map of the newly referenced field. Also:
- A
UNIONdeclaration can appear only within aSTRUCTUREdeclaration.- The amount of memory used by a union is that of its biggest map.
- Within a
UNIONdeclaration, the order of theMAPstatements is not relevant.The
UNIONline is part of an inherently multiline group of statements, and neither theUNIONline nor theENDUNIONline has any special indication of continuation. You do not put a nonblank in column six, nor an&in column one.Each field-declaration in a map declaration can be one of the following:
- Structure declaration
- Record
- Union declaration
- Declaration of a typed data field
Example
Declare the structure
/STUDENT/to contain eitherNAME,CLASS, andMAJOR,orNAME,CLASS,CREDITS, andGRAD_DATE:
STRUCTURE /STUDENT/CHARACTER*32 NAMEINTEGER*2 CLASSUNIONMAPCHARACTER*16 MAJOREND MAPMAPINTEGER*2 CREDITSCHARACTER*8 GRAD_DATEEND MAPEND UNIONEND STRUCTURERECORD /STUDENT/ PERSONIn the above example, the variable
PERSONhas the structure/STUDENT/, so:
PERSON.MAJORreferences a field from the first map;PERSON.CREDITSreferences a field from the second map.- If the variables of the first map field are initialized, and then the program references the variable
PERSON.MAJOR, the first map becomes active, and the variables of the second map become undefined.
VIRTUALThe
VIRTUALstatement is treated the same as the
DIMENSIONstatement.
VIRTUALa(d)[,a(d)]...
Parameter Description a Name of an array a(d) Specifies the dimension of the array. It is a list of 1 to 7 declarators separated by commas
Description
The
VIRTUALstatement has the same form and effect as theDIMENSIONstatement. It is included for compatibility with older versions of FORTRAN.Example
VIRTUAL M(4,4), V(1000)...END
VOLATILEThe
VOLATILEstatement prevents optimization on the specified items.
VOLATILEnlist
Parameter Description nlist List of variables, arrays, or common blocks
Description
The
VOLATILEstatement prevents optimization on the items in the list. Programs relying on it are usually nonportable.Example
Example:
VOLATILE:![]()
PROGRAM FFTINTEGER NODE*2, NSTEPS*2REAL DELTA, MAT(10,10), V(1000), X, ZCOMMON /INI/ NODE, DELTA, V...VOLATILE V, Z, MAT, /INI/...EQUIVALENCE ( X, V )...In the above example, the array
V, the variableZ, and the common block/INI/are explicitly specified asVOLATILE. The variableXisVOLATILEthrough an equivalence.
WRITEThe
WRITEstatement writes data from the list to a file.
Note For tape I/O, use theTOPEN()routines.
WRITE([UNIT=]u[,[FMT=]f][, IOSTAT=ios][, REC=rn][, ERR=s])iolist
WRITE([UNIT=]u,[NML=]grname[, IOSTAT=ios][, ERR=s])
The options can be specified in any order.
An alternate for the
REC=rn form is allowed, as follows:![]()
WRITE(u'rn... )iolist![]()
See Example 3, later on in this section.
Description
Unit Identifier
u is either an external unit identifier or an internal file identifier.
An external unit identifier must be one of the following:
- A nonnegative integer expression
- An asterisk, identifying
stdout, which is normally connected to the consoleIf the optional characters
UNIT=are omitted from the unit specifier, then u must be the first item in the list of specifiers.Format Identifier
f is a format identifier and can be:
- An asterisk (
*), indicating list-directed I/O. See List-Directed I/O for more information.- The label of a
FORMATstatement that appears in the same program unit- An integer variable name that has been assigned the label of a
FORMATstatement that appears in the same program unit- A character expression or integer array that specifies the format string. This is called a runtime format or a variable format. The integer array is nonstandard.
![]()
See Runtime Formats for details on formats evaluated at runtime.
If the optional characters,
FMT=, are omitted from the format specifier, then f must appear as the second argument for a formatted write; otherwise, it must not appear at all.f must not be an asterisk for direct access.
f can be an asterisk for internal files.
![]()
If a file is connected for formatted I/O, unformatted data transfer is prohibited, and vice versa.
I/O Status Specifier
ios must be an integer variable, integer array element, or integer record field.
Record Number
rn must be a positive integer expression. This argument can appear only for direct-access files. rn can be specified for internal files.
![]()
Error Specifier
s must be the label of an executable statement in the same program unit in which this
WRITEstatement occurs.Output List
iolist can be empty, or it can contain output items or implied
DOlists. The output items must be one of the following:
- Variables
- Substrings
- Arrays
- Array elements
- Record fields
- Any other expression
A simple unsubscripted array name specifies all of the elements of the array in memory storage order, with the leftmost subscript increasing more rapidly.
Implied DO lists are described in Implied DO Lists.
If the output item is a character expression that employs the concatenation operator, the length specifiers of its operands can be an asterisk (
*). This rule is nonstandard.![]()
If a function appears in the output list, that function must not cause an input/output statement to be executed.
Namelist-Directed
WRITEThe second form of
WRITEis used to output the items of the specified namelist group. Here, grname is the name of the list previously defined in aNAMELISTstatement.Execution
Execution proceeds as follows:
1. The file associated with the specified unit is determined.
- The format, if specified, is established. The file is positioned appropriately prior to data transfer.
2. If the output list is not empty, data is transferred from the list to the file.
- Data is edited according to the format, if specified.
3. In the second form of namelist-directedWRITE, the data is transferred from the items of the specified namelist group according to the rules of namelist-directed output.4. The file is repositioned appropriately after the data transfer.5. If ios is specified, and no error occurs, it is set to zero; otherwise, it is set to a positive value.6. If s is specified and an error occurs, control is transferred to s.Restrictions
- Output from an exception handler is unpredictable.
- If you make your own exception handler, do not do any FORTRAN output from it. If you must do some, then call abort right after the output. Doing so reduces the relative risk of a system freeze. FORTRAN I/O from an exception handler amounts to recursive I/O. See the next paragraph.
- Recursive I/O does not work reliably.
- If you list a function in an I/O list, and if that function does I/O, then during runtime, the execution may freeze, or some other unpredictable problem results. This risk exists independent of using parallelization.
- Example: Recursive I/O fails intermittently:
WRITE(*,*) x, f(x) Not allowed because f() does I/O.ENDFUNCTION F(X)WRITE(*,*) XRETURNENDComments
If u specifies an external unit that is not connected to a file, an implicit
OPENoperation is performed that is equivalent to opening the file with the following options:
OPEN(u, FILE='FORT.u', STATUS='UNKNOWN',fmt
& ACCESS='SEQUENTIAL', FORM=)The value of fmt is
'FORMATTED'if the write is formatted, and'UNFORMATTED'otherwise.A simple unsubscripted array name specifies all of the elements of the array in memory storage order, with the leftmost subscript increasing more rapidly.
The record number for direct-access files starts from one onwards.
Namelist-directed output is permitted on sequential access files only.
Examples
Example 1: Formatted write with trap I/O errors and I/O status:
WRITE( 1, 2, ERR=8, IOSTAT=N ) X, YRETURN...8 WRITE( *, * ) 'I/O error # ', N, ', on 1'STOPENDExample 2: Direct, unformatted write, trap I/O errors, and I/O status:
...WRITE( 1, REC=3, IOSTAT=N, ERR=8 ) V...4 CONTINUERETURN8 WRITE( *, * ) 'I/O error # ', N, ', on 1'ENDExample 3: Direct, alternate syntax (equivalent to above example):
...WRITE( 1 ' 3, IOSTAT=N, ERR=8 ) V
...4 CONTINUERETURN8 WRITE( *, * ) 'I/O error # ', N, ', on 1'END![]()
Example 4: List-directed write to screen:
WRITE( *, * ) A, VorPRINT *, A, VExample 5: Formatted write to an internal file:
CHARACTER CA*16, L*8 /'abcdefgh'/, R*8 /'ijklmnop'/WRITE( CA, 1 ) L, R1 FORMAT( 2 A8 )Example 6: Write an entire array
:
DIMENSION V(5)WRITE( 3, '(5F4.1)') VExample 7: Namelist-directed write:.
CHARACTER SAMPLE*16LOGICAL NEW*4REAL DELTA*4NAMELIST /G/ SAMPLE, NEW, DELTA...WRITE( 1, G )orWRITE( UNIT=1, NML=G )orWRITE( 1, NML=G )
|
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |