18. Fortran programming style
There are many different programming styles, but we will try to give some
general guidelines that are fairly non-controversial.
Portability
To ensure portability, use only standard Fortran 77. The only
exception we have allowed in this tutorial is to use lower case letters today.
Program structure
The overall program structure should be modular. Each subprogram
should solve a well-defined task. Many people prefer to write
each subprogram in a separate file.
Comments
Let us repeat this: Write legible code, but also add comments
in the source explaining what is happening! It is especially important
to have a good header for each subprogram that explains each
input/output argument and what the subprogram does.
Indentation
Always use proper indentation for loops and if blocks as
demonstrated in this tutorial.
Variables
Always declare all variables. Implicit type declaration is bad!
Try to stick to maximum 6 characters for variable names,
or at the very least make sure the 6 first characters are unique.
Subprograms
Never let functions have "side effects", i.e. do not change
the value of the input parameters. Use subroutines in
such cases.
In the declarations, separate parameters, common blocks, and local variables.
Minimize the use of common blocks.
Goto
Minimize the use of goto. Unfortunately it is necessary to use
goto in some loops since while is not standard Fortran.
Arrays
In many cases it is best to declare all large arrays in the main program
and then pass them as arguments to the various subroutines. This way
all the space allocation is done in one place. Remember to pass
the leading dimensions. Avoid unnecessary "reshaping" of matrices.
Efficiency concerns
When you have a double loop accessing a two-dimensional array,
it is usually best to have the first (row) index in the
innermost loop. This is because of the storage scheme in Fortran.
When you have if-then-elseif statements with multiple conditions,
try to place the most likely conditions first.
[Fortran Tutorial Home]
boman@sccm.stanford.edu