User:Bethlehem4/sandbox

This is a comprehensive overview of features of the Fortran 95 language,

これは、[ja:FORTRAN#Fortran 95]] 言語の特徴の概括的なオーバービューである.

the version supported by almost all existing Fortran compilers. このバージョンは現存するほとんどのFortranコンパイラにサポートされている.

Included are the additional features of TR-15581:Enhanced Data Type Facilities, that have been universally imlemented.

TR-15581:Enhanced Data Type Facilitiesは広くインプリメントされている.

Old features that have been superseded by new ones are not described — few of those historic features are used in modern programs (although most have been retained in the language to maintain backward compatibility). Although the current standard is Fortran 2008, even many of those features first introduced into Fortran 2003 are still being implemented. The additional features of Fortran 2003 and Fortran 2008 are described by Metcalf, Reid and Cohen.

Language elements
Note. Fortran is case-insensitive. The convention of writing Fortran keywords in upper case and all other names in lower case is adopted in this article (except, by way of contrast, in the input/output descriptions (Data transfer and Operations on external files)).

Basics
The basic component of the Fortran language is its character set. Its members are:
 * the letters A ... Z and a ... z (which are equivalent outside a character context)
 * the numerals 0 ... 9
 * the underscore _
 * the special characters

Tokens that have a syntactic meaning to the compiler are built from those components. There are six classes of tokens:

From the tokens, statements are built. These can be coded using the new free source form which does not require positioning in a rigid column structure:

Note the trailing comments and the trailing continuation mark. There may be 39 continuation lines, and 132 characters per line. Blanks are significant. Where a token or character constant is split across two lines:               ... start_of&amp; &amp;_name ...  'a very long &amp; &amp;string'  a leading  on the continued line is also required.

Automatic conversion of source form for existing programs can be carried out by convert.f90.

Its options are:
 * significant blank handling;
 * indentation;
 * CONTINUE replaced by END DO;
 * name added to subprogram END statement; and
 * INTEGER*2 etc. syntax converted.

Intrinsic data types
Fortran has five intrinsic data types:,  ,  ,   and. Each of those types can be additionally characterized by a kind. Kind, basically, defines internal representation of the type: for the three numeric types, it defines the precision and range, and for the other two, the specifics of storage representation. Thus, it is an abstract concept which models the limits of data types' representation; it is expressed as a member of a set of whole numbers (e.g. it may be {1, 2, 4, 8} for integers, denoting bytes of storage), but those values are not specified by the Standard and not portable. For every type, there is a default kind, which is used if no kind is explicitly specified. For each intrinsic type, there is a corresponding form of literal constant. The numeric types  and   can only be signed (there is no concept of sign for type  ).

Integer literal constants of the default kind take the form: 1  0   -999   32767   +10

Kind can be defined as a named constant. If the desired range is ±10kind, the portable syntax for defining the appropriate kind,  is:

INTEGER, PARAMETER :: two_bytes = SELECTED_INT_KIND(4)

that allows subsequent definition of constants of the form: -1234_two_bytes  +1_two_bytes

Here,  is the kind type parameter; it can also be an explicit default integer literal constant, like -1234_2 but such use is non-portable.

The KIND function supplies the value of a kind type parameter: KIND(1)           KIND(1_two_bytes)

and the  function supplies the actual decimal range (so the user must make the actual mapping to bytes):

RANGE(1_two_bytes)

Also, in  (initialization) statements, binary (B), octal (O) and hexadecimal (Z) constants may be used (often informally referred to as "BOZ constants"):

B'01010101'  O'01234567'   Z'10fa'

There are at least two real kinds—the default, and one with greater precision (this replaces ). functions returns the kind number for desired range and precision; for at least 9 decimal digits of precision and a range of 10−99 to 1099, it can be specified as: INTEGER, PARAMETER :: long = SELECTED_REAL_KIND(9, 99) and literals subsequently specified as: 1.7_long Also, there are the intrinsic functions KIND(1.7_long)  PRECISION(1.7_long)   RANGE(1.7_long) that give in turn the kind type value, the actual precision (here at least 9), and the actual range (here at least 99).

data type is built of two integer or real components: (1, 3.7_long)

There are only two basic values of logical constants:  and. Here, there may also be different kinds. Logicals don't have their own kind inquiry functions, but use the kinds specified for s; default kind of   is the same as of INTEGER. .FALSE. .true._one_byte

and the  function operates as expected: KIND(.TRUE.)

The forms of literal constants for  data type are: 'A string'  "Another"   'A "quote"'

(the last being an empty string). Different kinds are allowed (for example, to distinguish ASCII and UNICODE strings), but not widely supported by compilers. Again, the kind value is given by the  function: KIND('ASCII')

Number model and intrinsic functions
The numeric types are based on number models with associated inquiry functions (whose values are independent of the values of their arguments; arguments are used only to provide kind). These functions are important for portable numerical software:

Scalar variables
Scalar variables corresponding to the five intrinsic types are specified as follows:

where the optional  parameter specifies a non-default kind, and the   notation delimits the type and attributes from variable name(s) and their optional initial values, allowing full variable specification and initialization to be typed in one statement (in previous standards, attributes and initializers had to be declared in several statements). While it is not required in above examples (as there are no additional attributes and initialization), most Fortran-90 programmers acquire the habit to use it everywhere.

specifier is applicable only to s and specifies the string length (replacing the older   form). The explicit  and   specifiers are optional:

CHARACTER(2, Kanji) :: kanji_word

works just as well.

There are some other interesting character features. Just as a substring as in CHARACTER(80) :: line ... = line(i:i)                    ! substring was previously possible, so now is the substring '0123456789'(i:i)

Also, zero-length strings are allowed: line(i:i-1)      ! zero-length string

Finally, there is a set of intrinsic character functions, examples being:

Derived data types
For derived data types, the form of the type must be defined first:

and then, variables of that type can be defined:

To select components of a derived type,  qualifier is used: you%age

Literal constants of derived types have the form  : you = person('Smith', 23.5) which is known as a structure constructor. Definitions may refer to a previously defined type:

and for a variable of type triangle, as in TYPE(triangle) t each component of type   is accessed as: t%a  t%b   t%c which, in turn, have ultimate components of type real: t%a%x  t%a%y   t%b%x   etc. (Note that the   qualifier was chosen rather than dot  because of potential ambiguity with operator notation, like  ).

Implicit and explicit typing
Unless specified otherwise, all variables starting with letters I, J, K, L, M and N are default s, and all others are default  ; other data types must be explicitly declared. This is known as implicit typing and is a heritage of early FORTRAN days. Those defaults can be overridden by   statements, like: However, it is a good practice to explicitly type all variables, and this can be forced by inserting the statement at the beginning of each program unit.

Arrays
Arrays are considered to be variables in their own right. Every array is characterized by its type, rank, and shape (which defines the extents of each dimension). Bounds of each dimension are by default 1 and size, but arbitrary bounds can be explicitly specified. keyword is optional and considered an attribute; if omitted, the array shape must be specified after array-variable name. For example: declares two arrays, rank-1 and rank-2, whose elements are in column-major order. Elements are, for example, a(1) a(i*j) and are scalars. The subscripts may be any scalar integer expression.

Sections are parts of the array variables, and are arrays themselves: Whole arrays and array sections are array-valued objects. Array-valued constants (constructors) are available, enclosed in : (/ 1, 2, 3, 4 /) (/ ( (/ 1, 2, 3 /), i = 1, 4) /) (/ (i, i = 1, 9, 2) /) (/ (0, i = 1, 100) /) (/ (0.1*i, i = 1, 10) /) making use of an implied-DO loop notation. Fortran 2003 allows the use of brackets:  and instead of the first two examples above, and many compilers support this now. A derived data type may, of course, contain array components: TYPE triplet REAL, DIMENSION(3) :: vertex END TYPE triplet TYPE(triplet), DIMENSION(4) :: t so that t(2)          is a scalar (a structure) t(2)%vertex   is an array component of a scalar

Data initialization
Variables can be given initial values as specified in a specification statement: REAL, DIMENSION(3) :: a = (/ 0.1, 0.2, 0.3 /) and a default initial value can be given to the component of a derived data type: TYPE triplet REAL, DIMENSION(3) :: vertex = 0.0 END TYPE triplet When local variables are initialized within a procedure they implicitly acquire the SAVE attribute: REAL, DIMENSION(3) :: point = (/ 0.0, 1.0, -1.0 /) This declaration is equivalent to: REAL, DIMENSION(3), SAVE :: point = (/ 0.0, 1.0, -1.0 /) for local variables within a subroutine or function. The SAVE attribute causes local variables to retain their value after a procedure call and then to initialize the variable to the saved value upon returning to the procedure.

attribute
A named constant can be specified directly by adding the  attribute and the constant values to a type statement:

DATA statement
The  statement can be used for scalars and also for arrays and variables of derived type. It is also the only way to initialise just parts of such objects, as well as to initialise to binary, octal or hexadecimal values:

Initialization expressions
The values used in  and   statements, or with these attributes, are constant expressions that may include references to: array and structure constructors, elemental intrinsic functions with integer or character arguments and results, and the six transformational functions   and   (see Intrinsic procedures):

Specification expressions
It is possible to specify details of variables using any non-constant, scalar, integer expression that may also include inquiry function references:

Scalar numeric
The usual arithmetic operators are available —  (given here in increasing order of precedence).

Parentheses are used to indicate the order of evaluation where necessary: The rules for scalar numeric expressions and assignments accommodate the non-default kinds. Thus, the mixed-mode numeric expression and assignment rules incorporate different kind type parameters in an expected way: real2 = integer0 + real1

converts  to a real value of the same kind as  ; the result is of same kind, and is converted to the kind of   for assignment.

These functions are available for controlled rounding of real numbers to integers:
 * : round to nearest integer, return integer result
 * : round to nearest integer, return real result
 * : truncate (round towards zero), return integer result
 * : truncate (round towards zero), return real result
 * : smallest integral value not less than argument (round up) (Fortran-90)
 * : largest integral value not greater than argument (round down) (Fortran-90)

Scalar relational operations
For scalar relational operations of numeric types, there is a set of built-in operators: <   <=    ==   /=   >   >= .LT. .LE. .EQ. .NE. .GT. .GE. (the forms above are new to Fortran-90, and older equivalent forms are given below them). Example expressions:

Scalar characters
In the case of scalar characters and given CHARACTER(8) result

it is legal to write

Concatenation is performed by the operator '//'.

Derived-data types
No built-in operations (except assignment, defined on component-by component basis) exist between derived data types mutually or with intrinsic types. The meaning of existing or user-specified operators can be (re)defined though: we can write Notice the "overloaded" use of the intrinsic symbol  and the named operator,. A difference between the two cases is that, for an intrinsic operator token, the usual precedence rules apply, whereas for named operators, precedence is the highest as a unary operator or the lowest as a binary one. In vector3 = matrix    *    vector1  + vector2 vector3 =(matrix .times. vector1) + vector2 the two expressions are equivalent only if appropriate parentheses are added as shown. In each case there must be defined, in a module, procedures defining the operator and assignment, and corresponding operator-procedure association, as follows: The string concatenation function is a more elaborated version of that shown already in Basics. Note that in order to handle the error condition that arises when the two strings together exceed the preset 80-character limit, it would be safer to use a subroutine to perform the concatenation (in this case operator-overloading would not be applicable.)

Defined operators such as these are required for the expressions that are allowed also in structure constructors (see Derived-data types): str1 = string(2, char1//char2) ! structure constructor

Arrays
In the case of arrays then, as long as they are of the same shape (conformable), operations and assignments are extended in an obvious way, on an element-by-element basis. For example, given declarations of REAL, DIMENSION(10, 20) :: a, b, c REAL, DIMENSION(5)     :: v, w LOGICAL                    flag(10, 20) it can be written: a = b                                      ! whole array assignment c = a/b                                    ! whole array division and assignment c = 0. ! whole array assignment of scalar value w = v + 1. ! whole array addition to scalar value w = 5/v + a(1:5, 5)                        ! array division, and addition to section flag = a==b                                ! whole array relational test and assignment c(1:8, 5:10) = a(2:9, 5:10) + b(1:8, 15:20) ! array section addition and assignment v(2:5) = v(1:4)                            ! overlapping section assignment The order of expression evaluation is not specified in order to allow for optimization on parallel and vector machines. Of course, any operators for arrays of derived type must be defined.

Some real intrinsic functions that are useful for numeric computations are: CEILING        FLOOR         MODULO (also integer) EXPONENT       FRACTION NEAREST        RRSPACING     SPACING SCALE          SET_EXPONENT These are array valued for array arguments (elemental), like all FORTRAN 77 functions (except LEN): INT            REAL          CMPLX AINT           ANINT         NINT ABS            MOD           SIGN DIM            MAX           MIN

SQRT           EXP           LOG LOG10          SIN           COS TAN            ASIN          ACOS ATAN           ATAN2 SINH           COSH          TANH

AIMAG          CONJG

LGE            LGT           LLE LLT            ICHAR         CHAR INDEX (the last seven are for characters).

Branching and conditions
The simple  label exists, but is usually avoided &mdash; in most cases, a more specific branching construct will accomplish the same logic with more clarity.

The simple conditional test is the  statement: A full-blown  construct is illustrated by:

CASE construct
The  construct is a replacement for the computed , but is better structured and does not require the use of statement labels: Each  selector list may contain a list and/or range of integers, character or logical constants, whose values may not overlap within or between selectors:  CASE (1, 2, 7, 10:17, 23)  A default is available:  CASE DEFAULT  There is only one evaluation, and only one match.

DO construct
A simplified but sufficient form of the  construct is illustrated by where we note that loops may be optionally named so that any EXIT or CYCLE statement may specify which loop is meant.

Many, but not all, simple loops can be replaced by array expressions and assignments, or by new intrinsic functions. For instance  tot = 0. DO i = m, n            tot = tot + a(i) END DO  becomes simply  tot = SUM( a(m:n) ) 

Definitions
In order to discuss this topic we need some definitions. In logical terms, an executable program consists of one main program and zero or more subprograms (or procedures) - these do something. Subprograms are either functions or subroutines, which are either external, internal or module subroutines. (External subroutines are what we knew from FORTRAN 77.)

From an organizational point of view, however, a complete program consists of program units. These are either main programs, external subprograms or modules and can be separately compiled.

An example of a main (and complete) program is: An example of a main program and an external subprogram, forming an executable program, is: The form of a function is: The form of reference of a function is:

Internal procedures
An internal subprogram is one contained in another (at a maximum of one level of nesting) and provides a replacement for the statement function: We say that  is the host of , and that   obtains access to entities in  by host association (e.g. to  ), whereas is a local variable to.

The scope of a named entity is a scoping unit, here less, and.

The names of program units and external procedures are global, and the names of implied-DO variables have a scope of the statement that contains them.

Modules
Modules are used to package  global data (replaces COMMON and BLOCK DATA from Fortran 77); type definitions (themselves a scoping unit); subprograms (which among other things replaces the use of ENTRY from Fortran 77); interface blocks (another scoping unit, see Interface blocks); namelist groups (see any textbook). </LI></UL> An example of a module containing a type definition, interface block and function subprogram is: and the simple statement <PRE> USE interval_arithmetic </PRE> provides use association to all the module's entities. Module subprograms may, in turn, contain internal subprograms.

Controlling accessibility
The  and   attributes are used in specifications in modules to limit the scope of entities. The attribute form is <PRE> REAL, PUBLIC    :: x, y, z           ! default INTEGER, PRIVATE :: u, v, w </PRE> and the statement form is <PRE> PUBLIC :: x, y, z, OPERATOR(.add.) PRIVATE :: u, v, w, ASSIGNMENT(=), OPERATOR(*) </PRE> The statement form has to be used to limit access to operators, and can also be used to change the overall default: <PRE> PRIVATE                       ! sets default for module PUBLIC :: only_this </PRE> For derived types there are three possibilities: the type and its components are all PUBLIC, the type is PUBLIC and its components PRIVATE (the type only is visible and one can change its details easily), or all of it is PRIVATE (for internal use in the module only):

The  statement's purpose is to gain access to entities in a module. It has options to resolve name clashes if an imported name is the same as a local one: <PRE> USE mine, local_list =&gt; list </PRE> or to restrict the used entities to a specified set: <PRE> USE mine, ONLY : list </PRE> These may be combined: <PRE> USE mine, ONLY : local_list =&gt; list </PRE>

Arguments
We may specify the intent of dummy arguments: <PRE> SUBROUTINE shuffle (ncards, cards) INTEGER, INTENT(IN) :: ncards INTEGER, INTENT(OUT), DIMENSION(ncards) :: cards </PRE> Also, INOUT is possible: here the actual argument must be a variable (unlike the default case where it may be a constant).

Arguments may be optional: <PRE> SUBROUTINE mincon(n, f, x, upper, lower, equalities, inequalities, convex, xstart) REAL, OPTIONAL, DIMENSION :: upper, lower : </PRE> allows us to call  by <PRE> CALL mincon (n, f, x, upper) :       IF (PRESENT(lower)) THEN   ! test for presence of actual argument : </PRE> Arguments may be keyword rather than positional (which come first): <PRE> CALL mincon(n, f, x, equalities=0, xstart=x0) </PRE> Optional and keyword arguments are handled by explicit interfaces, that is with internal or module procedures or with interface blocks.

Interface blocks
Any reference to an internal or module subprogram is through an interface that is 'explicit' (that is, the compiler can see all the details). A reference to an external (or dummy) procedure is usually 'implicit' (the compiler assumes the details). However, we can provide an explicit interface in this case too. It is a copy of the header, specifications and END statement of the procedure concerned, either placed in a module or inserted directly: An explicit interface is obligatory for: <UL> <LI>optional and keyword arguments; <LI>POINTER and TARGET arguments (see Pointers); <LI>POINTER function result; <LI>new-style array arguments and array functions (Array handling). </LI></UL> It allows full checks at compile time between actual and dummy arguments.

In general, the best way to ensure that a procedure interface is explicit is either to place the procedure concerned in a module or to use it as an internal procedure.

Overloading and generic interfaces
Interface blocks provide the mechanism by which we are able to define generic names for specific procedures: <PRE> INTERFACE gamma                  ! generic name FUNCTION sgamma(X)            ! specific name REAL (SELECTED_REAL_KIND( 6)) sgamma, x       END FUNCTION dgamma(X)            ! specific name REAL (SELECTED_REAL_KIND(12)) dgamma, x       END END INTERFACE </PRE> where a given set of specific names corresponding to a generic name must all be of functions or all of subroutines. If this interface is within a module, then it is simply <PRE> INTERFACE gamma MODULE PROCEDURE sgamma, dgamma END INTERFACE </PRE> We can use existing names, e.g. SIN, and the compiler sorts out the correct association.

We have already seen the use of interface blocks for defined operators and assignment (see Modules).

Recursion
Indirect recursion is useful for multi-dimensional integration. For <PRE> volume = integrate(fy, ybounds) </PRE> We might have <PRE> RECURSIVE FUNCTION integrate(f, bounds) ! Integrate f(x) from bounds(1) to bounds(2) REAL integrate INTERFACE FUNCTION f(x) REAL f, x          END FUNCTION f        END INTERFACE REAL, DIMENSION(2), INTENT(IN) :: bounds :    END FUNCTION integrate </PRE> and to integrate f(x, y) over a rectangle: <PRE> FUNCTION fy(y) USE func          ! module func contains function f       REAL fy, y        yval = y        fy = integrate(f, xbounds) END </PRE> Direct recursion is when a procedure calls itself, as in <PRE> RECURSIVE FUNCTION factorial(n) RESULT(res) INTEGER res, n       IF(n.EQ.0) THEN res = 1 ELSE res = n*factorial(n-1) END IF    END </PRE> Here, we note the  clause and termination test.

Pure Procedures
This is a feature for parallel computing.

In the FORALL Statement and Construct, any side effects in a function can impede optimization on a parallel processor—the order of execution of the assignments could affect the results. To control this situation, we add the  keyword to the or statement—an assertion that the procedure (expressed simply): <UL> <LI> alters no global variable, <LI> performs no I/O, <LI> has no saved variables (variables with the  attribute that retains values between invocations), and <LI>for functions, does not alter any of its arguments. </UL> A compiler can check that this is the case, as in: <PRE> PURE FUNCTION calculate (x) </PRE> All the intrinsic functions are pure.

Array handling
Array handling is included in Fortran for two main reasons: <UL> <LI>the notational convenience it provides, bringing the code closer to the underlying mathematical form; <LI>for the additional optimization opportunities it gives compilers (although  there are plenty of opportunities for degrading optimization too!). </LI></UL> At the same time, major extensions of the functionality in this area have been added. We have already met whole arrays above and here - now we develop the theme.

Zero-sized arrays
A zero-sized array is handled by Fortran as a legitimate object, without special coding by the programmer. Thus, in <PRE> DO i = 1,n x(i) = b(i) / a(i, i)       b(i+1:n) = b(i+1:n) - a(i+1:n, i) * x(i) END DO </PRE> no special code is required for the final iteration where. We note that a zero-sized array is regarded as being defined; however, an array of shape (0,2) is not conformable with one of shape (0,3), whereas <PRE> x(1:0) = 3 </PRE> is a valid 'do nothing' statement.

Assumed-shape arrays
These are an extension and replacement for assumed-size arrays. Given an actual argument like: <PRE> REAL, DIMENSION(0:10, 0:20) :: a       : CALL sub(a) </PRE> the corresponding dummy argument specification defines only the type and rank of the array, not its shape. This information has to be made available by an explicit interface, often using an interface block (see Interface blocks). Thus we write just <PRE> SUBROUTINE sub(da) REAL, DIMENSION :: da </PRE> and this is as if  were dimensioned (11,21). However, we can specify any lower bound and the array maps accordingly. The shape, not bounds, is passed, where the default lower bound is 1 and the default upper bound is the corresponding extent.

Automatic arrays
A partial replacement for the uses to which was put is provided by this facility, useful for local, temporary arrays, as in <PRE> SUBROUTINE swap(a, b)       REAL, DIMENSION       :: a, b        REAL, DIMENSION(SIZE(a)) :: work work = a       a = b        b = work END SUBROUTINE swap </PRE> The actual storage is typically maintained on a stack.

ALLOCATABLE and ALLOCATE
Fortran provides dynamic allocation of storage; it relies on a heap storage mechanism (and replaces another use of ). An example, for establishing a work array for a whole program, is The work array can be propagated through the whole program via a   statement in each program unit. We may specify an explicit lower bound and allocate several entities in one statement. To free dead storage we write, for instance, <PRE> DEALLOCATE(a, b) </PRE> Deallocation of arrays is automatic when they go out of scope.

Elemental operations, assignments and procedures
We have already met whole array assignments and operations: <PRE> REAL, DIMENSION(10) :: a, b  a = 0. ! scalar broadcast; elemental assignment b = SQRT(a)    ! intrinsic function result as array object </PRE> In the second assignment, an intrinsic function returns an array-valued result for an array-valued argument. We can write array-valued functions ourselves (they require an explicit interface): <PRE> PROGRAM test REAL, DIMENSION(3) :: a = (/ 1., 2., 3./),      &amp; b = (/ 2., 2., 2. /), r      r = f(a, b)      PRINT *, r   CONTAINS FUNCTION f(c, d)     REAL, DIMENSION :: c, d      REAL, DIMENSION(SIZE(c)) :: f      f = c*d        ! (or some more useful function of c and d)     END FUNCTION f   END PROGRAM test </PRE> Elemental procedures are specified with scalar dummy arguments that may be called with array actual arguments. In the case of a function, the shape of the result is the shape of the array arguments.

Most intrinsic functions are elemental and Fortran 95 extends this feature to non-intrinsic procedures, thus providing the effect of writing, in Fortran 90, 22 different versions, for ranks 0-0, 0-1, 1-0, 1-1, 0-2, 2-0, 2-2, ... 7-7, and is further an aid to optimization on parallel processors. An elemental procedure must be pure. The dummy arguments cannot be used in specification expressions (see above) except as arguments to certain intrinsic functions (, ,  , and the numeric inquiry ones, (see below).

WHERE
Often, we need to mask an assignment. This we can do using the , either as a statement: <PRE> WHERE (a /= 0.0) a = 1.0/a ! avoid division by 0 </PRE> (note: the test is element-by-element, not on whole array), or as a construct: <PRE> WHERE (a /= 0.0) a = 1.0/a b = a            ! all arrays same shape END WHERE </PRE> or <PRE> WHERE (a /= 0.0) a = 1.0/a ELSEWHERE a = HUGE(a) END WHERE </PRE> Further: <UL> <LI> it is permitted to mask not only the statement of the  construct, but also any  statement that it contains; <LI> a  construct may contain any number of masked  statements but at most one statement without a mask, and that must be the final one; <LI> constructs may be nested within one another, just constructs; <LI> a assignment statement is permitted to be a defined assignment, provided that it is elemental; <LI> a  construct may be named in the same way as other constructs. </LI></UL>

The FORALL Statement and Construct
When a  construct is executed, each successive iteration is performed in order and one after the other—an impediment to optimization on a parallel processor. <PRE> FORALL(i = 1:n) a(i, i) = x(i) </PRE> where the individual assignments may be carried out in any order, and even simultaneously. The  may be considered to be an array assignment expressed with the help of indices. <PRE> FORALL(i=1:n, j=1:n, y(i,j)/=0.) x(j,i) = 1.0/y(i,j) </PRE> with masking condition.

The  construct allows several assignment statements to be executed in order. <PRE> a(2:n-1,2:n-1) = a(2:n-1,1:n-2) + a(2:n-1,3:n) + a(1:n-2,2:n-1) + a(3:n,2:n-1) b(2:n-1,2:n-1) = a(2:n-1,2:n-1) </PRE> is equivalent to the array assignments <PRE> FORALL(i = 2:n-1, j = 2:n-1) a(i,j) = a(i,j-1) + a(i,j+1) + a(i-1,j) + a(i+1,j) b(i,j) = a(i,j) END FORALL </PRE> The  version is more readable.

Assignment in a is like an array assignment: as if all the expressions were evaluated in any order, held in temporary storage, then all the assignments performed in any order. The first statement must fully complete before the second can begin. A may be nested, and may include a. Procedures referenced within a must be pure.

Array elements
For a simple case: given <PRE> REAL, DIMENSION(100, 100) :: a </PRE> we can reference a single element as, for instance,. For a derived-data type like <PRE> TYPE fun_del REAL                 u        REAL, DIMENSION(3) :: du     END TYPE fun_del </PRE> we can declare an array of that type: <PRE> TYPE(fun_del), DIMENSION(10, 20) :: tar </PRE> and a reference like <PRE> tar(n, 2) </PRE> is an element (a scalar!) of type fun_del, but <PRE> tar(n, 2)%du </PRE> is an array of type real, and <PRE>                    tar(n, 2)%du(2) </PRE> is an element of it. The basic rule to remember is that an array element always has a subscript or subscripts qualifying at least the last name.

Array subobjects (sections)
The general form of subscript for an array section is       [lower] : [upper] [:stride]

(where [ ] indicates an optional item) as in <PRE> REAL a(10, 10) a(i, 1:n)               ! part of one row a(1:m, j)               ! part of one column a(i, : )                ! whole row a(i, 1:n:3)             ! every third element of row a(i, 10:1:-1)           ! row in reverse order a( (/ 1, 7, 3, 2 /), 1) ! vector subscript a(1, 2:11:2)            ! 11 is legal as not referenced a(:, 1:7)               ! rank two section </PRE> Note that a vector subscript with duplicate values cannot appear on the left-hand side of an assignment as it would be ambiguous. Thus, <PRE> b( (/ 1, 7, 3, 7 /) ) = (/ 1, 2, 3, 4 /) </PRE> is illegal. Also, a section with a vector subscript must not be supplied as an actual argument to an  or   dummy argument. Arrays of arrays are not allowed: <PRE> tar%du            ! illegal </PRE> We note that a given value in an array can be referenced both as an element and as a section: <PRE> a(1, 1)           ! scalar (rank zero) a(1:1, 1)         ! array section (rank one) </PRE> depending on the circumstances or requirements. By qualifying objects of derived type, we obtain elements or sections depending on the rule stated earlier: <PRE>

tar%u             ! array section (structure component) tar(1, 1)%u       ! component of an array element </PRE>

Arrays intrinsic functions
Vector and matrix multiply <PRE> DOT_PRODUCT       Dot product of 2 rank-one arrays MATMUL            Matrix multiplication </PRE> Array reduction <PRE> ALL               True if all values are true ANY               True if any value is true. Example: IF (ANY( a &gt; b)) THEN COUNT             Number of true elements in array MAXVAL            Maximum value in an array MINVAL            Minimum value in an array PRODUCT           Product of array elements SUM               Sum of array elements </PRE> Array inquiry <PRE> ALLOCATED         Array allocation status LBOUND            Lower dimension bounds of an array SHAPE             Shape of an array (or scalar) SIZE              Total number of elements in an array UBOUND            Upper dimension bounds of an array </PRE> Array construction <PRE> MERGE             Merge under mask PACK              Pack an array into an array of rank SPREAD            Replicate array by adding a dimension UNPACK            Unpack an array of rank one into an array under mask </PRE> Array reshape <PRE> RESHAPE           Reshape an array </PRE> Array manipulation <PRE> CSHIFT            Circular shift EOSHIFT           End-off shift TRANSPOSE         Transpose of an array of rank two </PRE> Array location <PRE> MAXLOC            Location of first maximum value in an array MINLOC            Location of first minimum value in an array </PRE>

Basics
Pointers are variables with the  attribute; they are not a distinct data type (and so no 'pointer arithmetic' is possible). <PRE> REAL, POINTER :: var </PRE> They are conceptually a descriptor listing the attributes of the objects (targets) that the pointer may point to, and the address, if any, of a target. They have no associated storage until it is allocated or otherwise associated (by pointer assignment, see below): <PRE> ALLOCATE (var) </PRE> and they are dereferenced automatically, so no special symbol required. In <PRE> var = var + 2.3 </PRE> the value of the target of var is used and modified. Pointers cannot be transferred via I/O. The statement <PRE> WRITE *, var </PRE> writes the value of the target of var and not the pointer descriptor itself.

A pointer can point to other pointers, and hence to their targets, or to a static object that has the  attribute: <PRE> REAL, POINTER :: object REAL, TARGET :: target_obj var =&gt; object                 ! pointer assignment var =&gt; target_obj </PRE> but they are strongly typed: <PRE> INTEGER, POINTER :: int_var var =&gt; int_var                ! illegal - types must match </PRE> and, similarly, for arrays the ranks as well as the type must agree.

A pointer can be a component of a derived type: <PRE> TYPE entry                      ! type for sparse matrix REAL value INTEGER index TYPE(entry), POINTER :: next ! note recursion END TYPE entry </PRE> and we can define the beginning of a linked chain of such entries: <PRE> TYPE(entry), POINTER :: chain </PRE> After suitable allocations and definitions, the first two entries could be addressed as <PRE> chain%value          chain%next%value chain%index          chain%next%index chain%next           chain%next%next </PRE> but we would normally define additional pointers to point at, for instance, the first and current entries in the list.

Association
A pointer's association status is one of <UL> <LI>undefined (initial state); <LI>associated (after allocation or a pointer assignment); <LI>disassociated: <PRE> DEALLOCATE (p, q) ! for returning storage NULLIFY (p, q)    ! for setting to 'null' </PRE> </LI></UL> Some care has to be taken not to leave a pointer 'dangling' by use of  on its target without nullifying any other pointer referring to it.

The intrinsic function  can test the association status of a defined pointer: <PRE> IF (ASSOCIATED(pointer)) THEN </PRE> or between a defined pointer and a defined target (which may, itself, be a pointer): <PRE> IF (ASSOCIATED(pointer, target)) THEN </PRE> An alternative way to initialize a pointer, also in a specification statement, is to use the  function: <PRE> REAL, POINTER, DIMENSION :: vector => NULL ! compile time vector => NULL                               ! run time </PRE>

Pointers in expressions and assignments
For intrinsic types we can 'sweep' pointers over different sets of target data using the same code without any data movement. Given the matrix manipulation y = B C z, we can write the following code (although, in this case, the same result could be achieved more simply by other means): <PRE> REAL, TARGET :: b(10,10), c(10,10), r(10), s(10), z(10) REAL, POINTER :: a, x, y     INTEGER mult :     DO mult = 1, 2 IF (mult == 1) THEN y =&gt; r             ! no data movement a =&gt; c           x =&gt; z         ELSE y =&gt; s             ! no data movement a =&gt; b           x =&gt; r         END IF         y = MATMUL(a, x)       ! common calculation END DO </PRE> For objects of derived type we have to distinguish between pointer and normal assignment. In <PRE> TYPE(entry), POINTER :: first, current :     first =&gt; current </PRE> the assignment causes first to point at current, whereas <PRE> first = current </PRE> causes current to overwrite first and is equivalent to <PRE> first%value = current%value first%index = current%index first%next =&gt; current%next </PRE>

Pointer arguments
If an actual argument is a pointer then, if the dummy argument is also a pointer, <ul> <li>it must have same rank,</li> <li>it receives its association status from the actual argument,</li> <li>it returns its final association status to the actual argument (note: the target may be undefined!),</li> <li>it may not have the  attribute (it would be ambiguous),</li> <li>it requires an interface block.</li> </ul> If the dummy argument is not a pointer, it becomes associated with the target of the actual argument: <PRE> REAL, POINTER :: a        : ALLOCATE (a(80, 80)) :    CALL sub(a) : SUBROUTINE sub(c) REAL c </PRE>

Pointer functions
Function results may also have the  attribute; this is useful if the result size depends on calculations performed in the function, as in <PRE> USE data_handler REAL x(100) REAL, POINTER :: y    : y =&gt; compact(x) </PRE> where the module data_handler contains <PRE> FUNCTION compact(x) REAL, POINTER :: compact REAL x ! A procedure to remove duplicates from the array x        INTEGER n        :              ! Find the number of distinct values, n       ALLOCATE(compact(n)) :             ! Copy the distinct values into compact END FUNCTION compact </PRE> The result can be used in an expression (but must be associated with a defined target).

Arrays of pointers
These do not exist as such: given <PRE> TYPE(entry) :: rows(n) </PRE> then <PRE> rows%next             ! illegal </PRE> would be such an object, but with an irregular storage pattern. For this reason they are not allowed. However, we can achieve the same effect by defining a derived data type with a pointer as its sole component: <PRE> TYPE row REAL, POINTER :: r    END TYPE </PRE> and then defining arrays of this data type: <PRE> TYPE(row) :: s(n), t(n) </PRE> where the storage for the rows can be allocated by, for instance, <PRE> DO i = 1, n       ALLOCATE (t(i)%r(1:i)) ! Allocate row i of length i    END DO </PRE> The array assignment <PRE> s = t </PRE> is then equivalent to the pointer assignments <PRE> s(i)%r =&gt; t(i)%r </PRE> for all components.

Pointers as dynamic aliases
Given an array <PRE >    REAL, TARGET :: table(100,100) </PRE>

that is frequently referenced with the fixed subscripts <PRE> table(m:n, p:q) </PRE> these references may be replaced by <PRE> REAL, DIMENSION, POINTER :: window :    window =&gt; table(m:n, p:q) </PRE> The subscripts of window are. Similarly, for <PRE> tar%u </PRE> (as defined in already), we can use, say, <PRE> taru =&gt; tar%u </PRE> to point at all the u components of tar, and subscript it as <PRE> taru(1, 2) </PRE> The subscripts are as those of tar itself. (This replaces yet more of .)

In the pointer association <PRE> pointer =&gt; array_expression </PRE> the lower bounds for  are determined as if   was applied to. Thus, when a pointer is assigned to a whole array variable, it inherits the lower bounds of the variable, otherwise, the lower bounds default to 1. Fortran 2003 allows specifying arbitrary lower bounds on pointer association, like <PRE> window(r:,s:) =&gt; table(m:n,p:q) </PRE> so that the bounds of  become. Fortran 95 does not have this feature; however, it can be simulated using the following trick (based on the pointer association rules for assumed shape array dummy arguments): <PRE> FUNCTION remap_bounds2(lb1,lb2,array) RESULT(ptr) INTEGER, INTENT(IN)                           :: lb1,lb2 REAL, DIMENSION(lb1:,lb2:), INTENT(IN), TARGET :: array REAL, DIMENSION, POINTER                 :: ptr ptr => array END FUNCTION : window => remap_bounds2(r,s,table(m:n,p:q)) </PRE>

The source code of an extended example of the use of pointers to support a data structure is in pointer.f90.

Intrinsic procedures
Most of the intrinsic functions have already been mentioned. Here, we deal only with their general classification and with those that have so far been omitted. All intrinsic procedures can be used with keyword arguments: <PRE> CALL DATE_AND_TIME (TIME=t) </PRE> and many have optional arguments.

The intrinsic procedures are grouped into four categories: <OL> <LI>elemental - work on scalars or arrays, e.g. ; <LI>inquiry - independent of value of argument (which may be undefined), e.g.   ; <LI>transformational - array argument with array result of different shape, e.g. ; <LI>subroutines, e.g.. </LI></OL> The procedures not already introduced are:: <PRE> Bit inquiry BIT_SIZE          Number of bits in the model Bit manipulation BTEST             Bit testing IAND              Logical AND IBCLR             Clear bit IBITS             Bit extraction IBSET             Set bit IEOR              Exclusive OR      IOR                Inclusive OR      ISHFT              Logical shift ISHFTC            Circular shift NOT               Logical complement Transfer function, as in           INTEGER :: i = TRANSFER('abcd', 0) (replaces part of EQUIVALENCE) Subroutines DATE_AND_TIME     Obtain date and/or time MVBITS            Copies bits RANDOM_NUMBER     Returns pseudorandom numbers RANDOM_SEED       Access to seed SYSTEM_CLOCK      Access to system clock CPU_TIME          Returns processor time in seconds </PRE>

Data transfer
(This is a subset only of the actual features and, exceptionally, lower case is used in the code examples.)

Formatted input/output
These examples illustrate various forms of I/O lists with some simple formats (see below): <PRE> integer            :: i   real, dimension(10) :: a   character(len=20)   :: word print "(i10)",    i   print "(10f10.3)", a   print "(3f10.3)",  a(1),a(2),a(3) print "(a10)",    word(5:14) print "(3f10.3)", a(1)*a(2)+i, sqrt(a(3:4)) </PRE> Variables, but not expressions, are equally valid in input statements using the  statement: <PRE> read "(i10)", i </PRE>

If an array appears as an item, it is treated as if the elements were specified in array element order.

Any pointers in an I/O list must be associated with a target, and transfer takes place between the file and the targets.

An item of derived type is treated as if the components were specified in the same order as in the type declaration, so <PRE> read "(8f10.5)", p, t ! types point and triangle </PRE> has the same effect as the statement <PRE> read "(8f10.5)", p%x, p%y, t%a%x, t%a%y, t%b%x, & t%b%y, t%c%x, t%c%y </PRE> An object in an I/O list is not permitted to be of a derived type that has a pointer component at any level of component selection. Note that a zero-sized array may occur as an item in an I/O list. Such an item corresponds to no actual data transfer.

The format specification may also be given in the form of a character expression: <PRE> character(len=*), parameter :: form="(f10.3)" :  print form, q </PRE> or as an asterisk—this is a type of I/O known as list-directed I/O (see below), in which the format is defined by the computer system: <PRE> print *, "Square-root of q = ", sqrt(q) </PRE> Input/output operations are used to transfer data between the storage of an executing program and an external medium, specified by a unit number. However, two I/O statements,   and a variant of, do not reference any unit number: this is referred to as terminal I/O. Otherwise the form is: <PRE> read (unit=4,    fmt="(f10.3)") q   read (unit=nunit, fmt="(f10.3)") q   read (unit=4*i+j, fmt="(f10.3)") a </PRE> where  is optional. The value may be any nonnegative integer allowed by the system for this purpose (but 0, 5 and 6 often denote the error, keyboard and terminal, respectively).

An asterisk is a variant—again from the keyboard: <PRE> read (unit=*, fmt="(f10.3)") q </PRE>

A read with a unit specifier allows exception handling: <PRE> read (unit=nunit, fmt="(3f10.3)", iostat=ios) a,b,c if (ios == 0) then !    Successful read - continue execution. :  else !    Error condition - take appropriate action. call error (ios) end if </PRE>

There a second type of formatted output statement, the statement: <PRE> write (unit=nout, fmt="(10f10.3)", iostat=ios) a </PRE>

Internal files
These allow format conversion between various representations to be carried out by the program in a storage area defined within the program itself. <PRE> integer, dimension(30)        :: ival integer                       :: key character(len=30)             :: buffer character(len=6), dimension(3), parameter :: form=(/ "(30i1)", "(15i2)","(10i3)" /) read (unit=*, fmt="(a30,i1)")     buffer, key read (unit=buffer, fmt=form (key)) ival(1:30/key) </PRE> If an internal file is a scalar, it has a single record whose length is that of the scalar. If it is an array, its elements, in array element order, are treated as successive records of the file and each has length that of an array element. An example using a  statement is <PRE> integer          :: day real             :: cash character(len=50) :: line : !  write into line write (unit=line, fmt="(a, i2, a, f8.2, a)") "Takings for day ", day, " are ", cash, " dollars" </PRE> that might write <PRE> Takings for day 3 are  4329.15 dollars </PRE>

List-directed I/O
An example of a read without a specified format for input is: <PRE> integer              :: i   real                  :: a   complex, dimension(2) :: field logical              :: flag character(len=12)    :: title character(len=4)     :: word :  read *, i, a, field, flag, title, word </PRE> If this reads the input record <PRE> 10 6.4 (1.0,0.0) (2.0,0.0) t test/ </PRE> (in which blanks are used as separators), then,  , ,, and   will acquire the values 10, 6.4, (1.0,0.0) and (2.0,0.0), and  respectively, while  remains unchanged.

Quotation marks or apostrophes are required as delimiters for a string that contains a blank.

Non-advancing I/O
This is a form of reading and writing without always advancing the file position to ahead of the next record. Whereas an advancing I/O statement always repositions the file after the last record accessed, a non-advancing I/O statement performs no such repositioning and may therefore leave the file positioned within a record. <PRE> character(len=3) :: key integer     :: u, s, ios :  read(unit=u, fmt="(a3)", advance="no", size=s, iostat=ios) key if (ios == 0) then :  else !   key is not in one record key(s+1:) = "" :  end if </PRE> A non-advancing read might read the first few characters of a record and a normal read the remainder.

In order to write a prompt to a terminal screen and to read from the next character position on the screen without an intervening line-feed, we can write: <PRE> write (unit=*, fmt="(a)", advance="no") "enter next prime number:" read (unit=*, fmt="(i10)") prime_number </PRE> Non-advancing I/O is for external files, and is not available for list-directed I/O.

Edit descriptors
It is possible to specify that an edit descriptor be repeated a specified number of times, using a repeat count:: <PRE> 10f12.3 </PRE> The slash edit descriptor (see below) may have a repeat count, and a repeat count can also apply to a group of edit descriptors, enclosed in parentheses, with nesting: <PRE> print "(2(2i5,2f8.2))", i(1),i(2),a(1),a(2), i(3),i(4),a(3),a(4) </PRE> Repeats are possible: <PRE> print "(10i8)", (/ (i(j), j=1,100) /) </PRE> will write 100 values eight to a line (apart from the last).

Data edit descriptors
<UL> <LI>Integer: <LI>Real: <LI>Complex: pairs of  or   edit descriptors <LI>Logical: <LI>Character: <LI>Derived types: are edited by the appropriate sequence of edit descriptors corresponding to the intrinsic types of the ultimate components of the derived type. <PRE> type, public :: string integer  :: length character(len=20) :: word end type string type(string) :: text read(unit=*, fmt="(i2, a)") text </PRE> </LI></UL>

Control edit descriptors
Control edit descriptors setting conditions:

The  (sign suppress) edit descriptor suppresses leading plus signs. To switch on plus sign printing, the (sign print) descriptor is used. The edit descriptor restores the option to the processor.

This descriptor remains in force for the remainder of the format specification, unless another of them is met.

Control edit descriptors for immediate processing: <UL> <LI>Tabulation: <PRE> read (unit=*, fmt="(t3,i4, tl4,i1, i2)") i,j,k </PRE> <LI>New records: <PRE> read "(i5,i3,/,i5,i3,i2)", i, j, k, l, m </PRE> Note that <PRE> print "(i5,4/,i5)", i, j </PRE> separates the two values by three blank records. <LI>Colon editing: terminates format control if there are no further items in an I/O list. <PRE> print "( i5, :, /, i5, :, /, i5)", (/(l(i), i=1,n)/) </PRE> stops new records if  equals 1 or 2. </LI></UL>

Unformatted I/O
This type of I/O should be used only in cases where the records are generated by a program on one computer, to be read back on the same computer or another computer using the same internal number representations: <PRE> open(unit=4, file='test', form='unformatted') read(unit=4) q  write(unit=nout, iostat=ios) a  ! no fmt= </PRE>

Direct-access files
This form of I/O is also known as random access or indexed I/O. Here, all the records have the same length, and each record is identified by an index number. It is possible to write, read, or re-write any specified record without regard to position. <PRE> integer, parameter :: nunit=2, length=100 real, dimension(length)           :: a   real, dimension(length+1:2*length) :: b   integer                            :: i, rec_length :  inquire (iolength=rec_length) a   open (unit=nunit, access="direct", recl=rec_length, status="scratch", action="readwrite") : !     Write array b to direct-access file in record 14 write (unit=nunit, rec=14) b  : ! !     Read the array back into array a   read (unit=nunit, rec=14) a   : do i = 1, length/2 a(i) = i  end do ! !     Replace modified record write (unit=nunit, rec=14) a </PRE> The file must be an external file and list-directed formatting and non-advancing I/O are unavailable.

Operations on external files
Once again, this is an overview only.

File positioning statements
<UL> <LI>The  statement: <PRE> backspace (unit=u [,iostat=ios])     ! where [ ] means optional </PRE> <LI>The  statement: <PRE> rewind (unit=u [,iostat=ios]) </PRE> <LI>The  statement: <PRE> endfile (unit=u [,iostat=ios]) </PRE> </LI></UL>

The open statement
The statement is used to connect an external file to a unit, create a file that is preconnected, or create a file and connect it to a unit. The syntax is <PRE> open (unit=u, status=st, action=act [,olist]) </PRE> where  is a list of optional specifiers. The specifiers may appear in any order. <PRE> open (unit=2, iostat=ios, file="cities", status="new", access="direct", &         action="readwrite", recl=100) </PRE> Other specifiers are  and.

The close statement
This is used to disconnect a file from a unit. <PRE> close (unit=u [,iostat=ios] [,status=st]) </PRE> as in <PRE> close (unit=2, iostat=ios, status="delete") </PRE>

The inquire statement
At any time during the execution of a program it is possible to inquire about the status and attributes of a file using this statement. Using a variant of this statement, it is similarly possible to determine the status of a unit, for instance whether the unit number exists for that system Another variant permits an inquiry about the length of an output list when used to write an unformatted record.

For inquire by unit: <PRE> inquire (unit=u, ilist) </PRE> or for inquire by file: <PRE> inquire (file=fln, ilist) </PRE> or for inquire by I/O list: <PRE> inquire (iolength=length) olist </PRE> As an example: <PRE> logical           :: ex, op   character (len=11) :: nam, acc, seq, frm integer           :: irec, nr   inquire (unit=2, exist=ex, opened=op, name=nam, access=acc, sequential=seq, form=frm, &            recl=irec, nextrec=nr) </PRE> yields <PRE> ex     .true. op     .true. nam     cities acc     DIRECT seq     NO frm      UNFORMATTED irec    100 nr      1 </PRE> (assuming no intervening read or write operations).

Other specifiers are.