1Fortran For C Programmers
2=========================
3
4This note is limited to essential information about Fortran so that
5a C or C++ programmer can get started more quickly with the language,
6at least as a reader, and avoid some common pitfalls when starting
7to write or modify Fortran code.
8Please see other sources to learn about Fortran's rich history,
9current applications, and modern best practices in new code.
10
11Know This At Least
12------------------
13* There have been many implementations of Fortran, often from competing
14  vendors, and the standard language has been defined by U.S. and
15  international standards organizations.  The various editions of
16  the standard are known as the '66, '77, '90, '95, 2003, 2008, and
17  (now) 2018 standards.
18* Forward compatibility is important.  Fortran has outlasted many
19  generations of computer systems hardware and software.  Standard
20  compliance notwithstanding, Fortran programmers generally expect that
21  code that has compiled successfully in the past will continue to
22  compile and work indefinitely.  The standards sometimes designate
23  features as being deprecated, obsolescent, or even deleted, but that
24  can be read only as discouraging their use in new code -- they'll
25  probably always work in any serious implementation.
26* Fortran has two source forms, which are typically distinguished by
27  filename suffixes.  `foo.f` is old-style "fixed-form" source, and
28  `foo.f90` is new-style "free-form" source.  All language features
29  are available in both source forms.  Neither form has reserved words
30  in the sense that C does.  Spaces are not required between tokens
31  in fixed form, and case is not significant in either form.
32* Variable declarations are optional by default.  Variables whose
33  names begin with the letters `I` through `N` are implicitly
34  `INTEGER`, and others are implicitly `REAL`.  These implicit typing
35  rules can be changed in the source.
36* Fortran uses parentheses in both array references and function calls.
37  All arrays must be declared as such; other names followed by parenthesized
38  expressions are assumed to be function calls.
39* Fortran has a _lot_ of built-in "intrinsic" functions.  They are always
40  available without a need to declare or import them.  Their names reflect
41  the implicit typing rules, so you will encounter names that have been
42  modified so that they have the right type (e.g., `AIMAG` has a leading `A`
43  so that it's `REAL` rather than `INTEGER`).
44* The modern language has means for declaring types, data, and subprogram
45  interfaces in compiled "modules", as well as legacy mechanisms for
46  sharing data and interconnecting subprograms.
47
48A Rosetta Stone
49---------------
50Fortran's language standard and other documentation uses some terminology
51in particular ways that might be unfamiliar.
52
53| Fortran | English |
54| ------- | ------- |
55| Association | Making a name refer to something else |
56| Assumed | Some attribute of an argument or interface that is not known until a call is made |
57| Companion processor | A C compiler |
58| Component | Class member |
59| Deferred | Some attribute of a variable that is not known until an allocation or assignment |
60| Derived type | C++ class |
61| Dummy argument | C++ reference argument |
62| Final procedure | C++ destructor |
63| Generic | Overloaded function, resolved by actual arguments |
64| Host procedure | The subprogram that contains a nested one |
65| Implied DO | There's a loop inside a statement |
66| Interface | Prototype |
67| Internal I/O | `sscanf` and `snprintf` |
68| Intrinsic | Built-in type or function |
69| Polymorphic | Dynamically typed |
70| Processor | Fortran compiler |
71| Rank | Number of dimensions that an array has |
72| `SAVE` attribute | Statically allocated |
73| Type-bound procedure | Kind of a C++ member function but not really |
74| Unformatted | Raw binary |
75
76Data Types
77----------
78There are five built-in ("intrinsic") types: `INTEGER`, `REAL`, `COMPLEX`,
79`LOGICAL`, and `CHARACTER`.
80They are parameterized with "kind" values, which should be treated as
81non-portable integer codes, although in practice today these are the
82byte sizes of the data.
83(For `COMPLEX`, the kind type parameter value is the byte size of one of the
84two `REAL` components, or half of the total size.)
85The legacy `DOUBLE PRECISION` intrinsic type is an alias for a kind of `REAL`
86that should be more precise, and bigger, than the default `REAL`.
87
88`COMPLEX` is a simple structure that comprises two `REAL` components.
89
90`CHARACTER` data also have length, which may or may not be known at compilation
91time.
92`CHARACTER` variables are fixed-length strings and they get padded out
93with space characters when not completely assigned.
94
95User-defined ("derived") data types can be synthesized from the intrinsic
96types and from previously-defined user types, much like a C `struct`.
97Derived types can be parameterized with integer values that either have
98to be constant at compilation time ("kind" parameters) or deferred to
99execution ("len" parameters).
100
101Derived types can inherit ("extend") from at most one other derived type.
102They can have user-defined destructors (`FINAL` procedures).
103They can specify default initial values for their components.
104With some work, one can also specify a general constructor function,
105since Fortran allows a generic interface to have the same name as that
106of a derived type.
107
108Last, there are "typeless" binary constants that can be used in a few
109situations, like static data initialization or immediate conversion,
110where type is not necessary.
111
112Arrays
113------
114Arrays are not types in Fortran.
115Being an array is a property of an object or function, not of a type.
116Unlike C, one cannot have an array of arrays or an array of pointers,
117although can can have an array of a derived type that has arrays or
118pointers as components.
119Arrays are multidimensional, and the number of dimensions is called
120the _rank_ of the array.
121In storage, arrays are stored such that the last subscript has the
122largest stride in memory, e.g. A(1,1) is followed by A(2,1), not A(1,2).
123And yes, the default lower bound on each dimension is 1, not 0.
124
125Expressions can manipulate arrays as multidimensional values, and
126the compiler will create the necessary loops.
127
128Allocatables
129------------
130Modern Fortran programs use `ALLOCATABLE` data extensively.
131Such variables and derived type components are allocated dynamically.
132They are automatically deallocated when they go out of scope, much
133like C++'s `std::vector<>` class template instances are.
134The array bounds, derived type `LEN` parameters, and even the
135type of an allocatable can all be deferred to run time.
136(If you really want to learn all about modern Fortran, I suggest
137that you study everything that can be done with `ALLOCATABLE` data,
138and follow up all the references that are made in the documentation
139from the description of `ALLOCATABLE` to other topics; it's a feature
140that interacts with much of the rest of the language.)
141
142I/O
143---
144Fortran's input/output features are built into the syntax of the language,
145rather than being defined by library interfaces as in C and C++.
146There are means for raw binary I/O and for "formatted" transfers to
147character representations.
148There are means for random-access I/O using fixed-size records as well as for
149sequential I/O.
150One can scan data from or format data into `CHARACTER` variables via
151"internal" formatted I/O.
152I/O from and to files uses a scheme of integer "unit" numbers that is
153similar to the open file descriptors of UNIX; i.e., one opens a file
154and assigns it a unit number, then uses that unit number in subsequent
155`READ` and `WRITE` statements.
156
157Formatted I/O relies on format specifications to map values to fields of
158characters, similar to the format strings used with C's `printf` family
159of standard library functions.
160These format specifications can appear in `FORMAT` statements and
161be referenced by their labels, in character literals directly in I/O
162statements, or in character variables.
163
164One can also use compiler-generated formatting in "list-directed" I/O,
165in which the compiler derives reasonable default formats based on
166data types.
167
168Subprograms
169-----------
170Fortran has both `FUNCTION` and `SUBROUTINE` subprograms.
171They share the same name space, but functions cannot be called as
172subroutines or vice versa.
173Subroutines are called with the `CALL` statement, while functions are
174invoked with function references in expressions.
175
176There is one level of subprogram nesting.
177A function, subroutine, or main program can have functions and subroutines
178nested within it, but these "internal" procedures cannot themselves have
179their own internal procedures.
180As is the case with C++ lambda expressions, internal procedures can
181reference names from their host subprograms.
182
183Modules
184-------
185Modern Fortran has good support for separate compilation and namespace
186management.
187The *module* is the basic unit of compilation, although independent
188subprograms still exist, of course, as well as the main program.
189Modules define types, constants, interfaces, and nested
190subprograms.
191
192Objects from a module are made available for use in other compilation
193units via the `USE` statement, which has options for limiting the objects
194that are made available as well as for renaming them.
195All references to objects in modules are done with direct names or
196aliases that have been added to the local scope, as Fortran has no means
197of qualifying references with module names.
198
199Arguments
200---------
201Functions and subroutines have "dummy" arguments that are dynamically
202associated with actual arguments during calls.
203Essentially, all argument passing in Fortran is by reference, not value.
204One may restrict access to argument data by declaring that dummy
205arguments have `INTENT(IN)`, but that corresponds to the use of
206a `const` reference in C++ and does not imply that the data are
207copied; use `VALUE` for that.
208
209When it is not possible to pass a reference to an object, or a sparse
210regular array section of an object, as an actual argument, Fortran
211compilers must allocate temporary space to hold the actual argument
212across the call.
213This is always guaranteed to happen when an actual argument is enclosed
214in parentheses.
215
216The compiler is free to assume that any aliasing between dummy arguments
217and other data is safe.
218In other words, if some object can be written to under one name, it's
219never going to be read or written using some other name in that same
220scope.
221```
222  SUBROUTINE FOO(X,Y,Z)
223  X = 3.14159
224  Y = 2.1828
225  Z = 2 * X ! CAN BE FOLDED AT COMPILE TIME
226  END
227```
228This is the opposite of the assumptions under which a C or C++ compiler must
229labor when trying to optimize code with pointers.
230
231Overloading
232-----------
233Fortran supports a form of overloading via its interface feature.
234By default, an interface is a means for specifying prototypes for a
235set of subroutines and functions.
236But when an interface is named, that name becomes a *generic* name
237for its specific subprograms, and calls via the generic name are
238mapped at compile time to one of the specific subprograms based
239on the types, kinds, and ranks of the actual arguments.
240A similar feature can be used for generic type-bound procedures.
241
242This feature can be used to overload the built-in operators and some
243I/O statements, too.
244
245Polymorphism
246------------
247Fortran code can be written to accept data of some derived type or
248any extension thereof using `CLASS`, deferring the actual type to
249execution, rather than the usual `TYPE` syntax.
250This is somewhat similar to the use of `virtual` functions in c++.
251
252Fortran's `SELECT TYPE` construct is used to distinguish between
253possible specific types dynamically, when necessary.  It's a
254little like C++17's `std::visit()` on a discriminated union.
255
256Pointers
257--------
258Pointers are objects in Fortran, not data types.
259Pointers can point to data, arrays, and subprograms.
260A pointer can only point to data that has the `TARGET` attribute.
261Outside of the pointer assignment statement (`P=>X`) and some intrinsic
262functions and cases with pointer dummy arguments, pointers are implicitly
263dereferenced, and the use of their name is a reference to the data to which
264they point instead.
265
266Unlike C, a pointer cannot point to a pointer *per se*, nor can they be
267used to implement a level of indirection to the management structure of
268an allocatable.
269If you assign to a Fortran pointer to make it point at another pointer,
270you are making the pointer point to the data (if any) to which the other
271pointer points.
272Similarly, if you assign to a Fortran pointer to make it point to an allocatable,
273you are making the pointer point to the current content of the allocatable,
274not to the metadata that manages the allocatable.
275
276Unlike allocatables, pointers do not deallocate their data when they go
277out of scope.
278
279A legacy feature, "Cray pointers", implements dynamic base addressing of
280one variable using an address stored in another.
281
282Preprocessing
283-------------
284There is no standard preprocessing feature, but every real Fortran implementation
285has some support for passing Fortran source code through a variant of
286the standard C source preprocessor.
287Since Fortran is very different from C at the lexical level (e.g., line
288continuations, Hollerith literals, no reserved words, fixed form), using
289a stock modern C preprocessor on Fortran source can be difficult.
290Preprocessing behavior varies across implementations and one should not depend on
291much portability.
292Preprocessing is typically requested by the use of a capitalized filename
293suffix (e.g., "foo.F90") or a compiler command line option.
294(Since the F18 compiler always runs its built-in preprocessing stage,
295no special option or filename suffix is required.)
296
297"Object Oriented" Programming
298-----------------------------
299Fortran doesn't have member functions (or subroutines) in the sense
300that C++ does, in which a function has immediate access to the members
301of a specific instance of a derived type.
302But Fortran does have an analog to C++'s `this` via *type-bound
303procedures*.
304This is a means of binding a particular subprogram name to a derived
305type, possibly with aliasing, in such a way that the subprogram can
306be called as if it were a component of the type (e.g., `X%F(Y)`)
307and receive the object to the left of the `%` as an additional actual argument,
308exactly as if the call had been written `F(X,Y)`.
309The object is passed as the first argument by default, but that can be
310changed; indeed, the same specific subprogram can be used for multiple
311type-bound procedures by choosing different dummy arguments to serve as
312the passed object.
313The equivalent of a `static` member function is also available by saying
314that no argument is to be associated with the object via `NOPASS`.
315
316There's a lot more that can be said about type-bound procedures (e.g., how they
317support overloading) but this should be enough to get you started with
318the most common usage.
319
320Pitfalls
321--------
322Variable initializers, e.g. `INTEGER :: J=123`, are _static_ initializers!
323They imply that the variable is stored in static storage, not on the stack,
324and the initialized value lasts only until the variable is assigned.
325One must use an assignment statement to implement a dynamic initializer
326that will apply to every fresh instance of the variable.
327Be especially careful when using initializers in the newish `BLOCK` construct,
328which perpetuates the interpretation as static data.
329(Derived type component initializers, however, do work as expected.)
330
331If you see an assignment to an array that's never been declared as such,
332it's probably a definition of a *statement function*, which is like
333a parameterized macro definition, e.g. `A(X)=SQRT(X)**3`.
334In the original Fortran language, this was the only means for user
335function definitions.
336Today, of course, one should use an external or internal function instead.
337
338Fortran expressions don't bind exactly like C's do.
339Watch out for exponentiation with `**`, which of course C lacks; it
340binds more tightly than negation does (e.g., `-2**2` is -4),
341and it binds to the right, unlike what any other Fortran and most
342C operators do; e.g., `2**2**3` is 256, not 64.
343Logical values must be compared with special logical equivalence
344relations (`.EQV.` and `.NEQV.`) rather than the usual equality
345operators.
346
347A Fortran compiler is allowed to short-circuit expression evaluation,
348but not required to do so.
349If one needs to protect a use of an `OPTIONAL` argument or possibly
350disassociated pointer, use an `IF` statement, not a logical `.AND.`
351operation.
352In fact, Fortran can remove function calls from expressions if their
353values are not required to determine the value of the expression's
354result; e.g., if there is a `PRINT` statement in function `F`, it
355may or may not be executed by the assignment statement `X=0*F()`.
356(Well, it probably will be, in practice, but compilers always reserve
357the right to optimize better.)
358
359Unless they have an explicit suffix (`1.0_8`, `2.0_8`) or a `D`
360exponent (`3.0D0`), real literal constants in Fortran have the
361default `REAL` type -- *not* `double` as in the case in C and C++.
362If you're not careful, you can lose precision at compilation time
363from your constant values and never know it.
364