source: LMDZ6/branches/LMDZ-QUEST/tools/fcm/doc/standards/fortran_standard.html @ 5327

Last change on this file since 5327 was 1578, checked in by jghattas, 13 years ago
  • Add fcm in LMDZ5/tools directory

It is no longer needed to have fcm in your environement PATH variable.
Now makelmdz_fcm takes by default this fcm. It is still possible to use
another fcm, using -fcm_path argument in makelmdz_fcm.

File size: 39.7 KB
Line 
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2
3<html>
4<head>
5  <title>Fortran coding standard for FCM</title>
6  <meta name="author" content="FCM team">
7  <meta name="descriptions" content="Fortran coding standard for FCM">
8  <meta name="keywords" content="Fortran, coding standard, FCM">
9  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
10  <link rel="StyleSheet" type="text/css" href="style.css">
11  <style type="text/css">
12  <!--
13  li, th, td {
14    padding: 3px;
15  }
16  td {
17    vertical-align: top;
18  }
19  mono {
20    font-family: monospace;
21  }
22  -->
23  </style>
24</head>
25
26<body>
27  <p align="right"><img src="logo.png" alt="Met Office logo" width="85"
28  height="85"></p>
29
30  <h1>Fortran coding standard for FCM</h1>
31
32  <p align="center">Last updated: 28 November 2006</a>
33
34  <p align="center">Met Office<br>
35  FitzRoy Road, Exeter<br>
36  Devon, EX1 3PB<br>
37  United Kingdom</p>
38
39  <p align="center">&copy; Crown copyright 2006. All rights reserved.</p>
40
41  <p align="center">Questions regarding this document or permissions to quote
42  from it should be directed to the <a href=
43  "mailto:iprmanager@metoffice.gov.uk">IPR Manager</a>.</p>
44 
45  <script type="text/javascript">
46  <!--
47  var out = 'For printing, please use the '
48  out    += '<a href="fcm-fortran-standard.pdf">PDF<\/a> version of the document.'
49  document.write ('<p align="center">')
50  document.write (out)
51  document.write ('<\/p>')
52  //-->
53  </script>
54
55  <h2>Contents</h2>
56
57  <p>Main contents:</p>
58
59  <ol>
60    <li><a href="#intro">Introduction</a></li>
61
62    <li>
63      <a href="#fcm">Programming Fortran for the FCM build system</a>
64
65      <ul>
66        <li><a href="#fcm-general">General</a></li>
67
68        <li><a href="#fcm-cpp">Use of C pre-processor</a></li>
69      </ul>
70    </li>
71
72    <li>
73      <a href="#fortran">Programming Fortran in general</a>
74
75      <ul>
76        <li><a href="#fortran-layout">Layout and formatting</a></li>
77
78        <li><a href="#fortran-style">Style</a></li>
79
80        <li><a href="#fortran-feature">Fortran features</a></li>
81      </ul>
82    </li>
83
84    <li><a href="#template">Program templates</a></li>
85  </ol>
86
87  <h2><a name="intro"></a>1. Introduction</h2>
88
89  <p>Fortran is the standard programming language at the Met Office for
90  developing scientific and research applications, in particular, for programs
91  running on the supercomputers. This document describes some guidelines that
92  should be followed by developers when writing Fortran code, especially for
93  code in systems hosted by FCM.</p>
94
95  <h2><a name="fcm"></a>2. Programming Fortran for the FCM build system</h2>
96
97  <h3><a name="fcm-general"></a>2.1 General</h3>
98
99  <p>To get the most out of the FCM build system, you should follow these
100  guidelines when you develop your code:</p>
101
102  <ol>
103    <li>Each source file should contain one and no more than one top level
104    program unit, (such as a PROGRAM, a standalone SUBROUTINE/FUNCTION or a
105    MODULE). All top level standalone program units in a source tree should be
106    uniquely named. ("Top level" means a standalone program unit that is
107    compilable independently, i.e. this rule does not restrict the naming and
108    placements of sub-programs in a CONTAINS section.) FCM may fail to set up
109    the dependency tree of your source correctly if you do not follow this rule.
110
111      <p>A clash of program unit names happens most often when you have multiple
112      versions of the same program unit in the same source tree. You should
113      design your code to avoid this situation. If it is not possible to do so,
114      you may have to use a pre-processor to ensure that there is only one copy
115      of each program unit in the source tree. Another situation where clashes
116      of program unit names may occur is when you are developing code that is
117      shared between several projects. In this case, you may want to agree with
118      the other projects a naming convention to define a unique namespace for
119      program units in each project. (E.g. some projects at the Met Office have
120      adopted a naming convention such that all shared program units in a
121      project are named with a unique prefix.)</p>
122    </li>
123
124    <li>All code should be written using the free source form. (At Fortran 95,
125    the free source form can have a maximum of 132 characters per line, and up
126    to 39 continuations in a Fortran statement.) The fixed source form is
127    obsolete, and is not supported by the interface file generators used by
128    FCM.</li>
129
130    <li>An interface should be provided when calling a SUBROUTINE or a FUNCTION.
131    Not only is this considered good practice, it also allows FCM to determine
132    the dependency relationship of your source files. An interface can be
133    provided in these ways:
134
135      <table summary="interface - internal procedures" width="100%" border="1">
136        <tr>
137          <th colspan="2">Internal sub-program</th>
138        </tr>
139
140        <tr>
141          <td colspan="2">Place sub-programs in the CONTAINS section of a
142          standalone program unit. There are two advantages for this approach.
143          Firstly, the sub-programs will get an automatic interface when the
144          container program unit is compiled. Secondly, it should be easier for
145          the compiler to provide optimisation when the sub-programs are
146          internal to the caller.  The disadvantage of this approach is that the
147          sub-programs are local to the caller, and so they cannot be called by
148          other program units.  Therefore, this approach is only suitable for
149          small sub-programs local to a particular program unit.
150       
151            <p>Note: One way to share a sub-program unit between several top
152            level program units is to make use of the Fortran INCLUDE statement.
153            You can write the sub-program unit in a separate file and place it
154            in the CONTAINS section of different program units using INCLUDE
155            statements.  The disadvantage of this approach is that when the
156            program is compiled, a copy of the sub-program unit will be embedded
157            within each of the top level program units. This may lead to an
158            increase in size of the executable, and so this approach is still
159            only suitable for small sub-programs local to a small number of
160            program units.</p>
161
162            <p>Example:</p>
163          </td>
164        </tr>
165
166        <tr>
167          <td width="50%">In the file "sub_prog.inc":
168
169            <pre>
170SUBROUTINE sub_prog (some, arg)
171! Some declarations ...
172! Some executable statements ...
173END SUBROUTINE sub_prog
174</pre>
175          </td>
176
177          <td>In the file "bar.f90":
178
179            <pre>
180SUBROUTINE bar (more, arg)
181! Some declarations ...
182! Some executable statements ...
183CALL sub_prog (some, arg)
184! More executable statements ...
185CONTAINS
186  INCLUDE 'sub_prog.inc'
187END SUBROUTINE bar
188</pre>
189          </td>
190        </tr>
191      </table>
192
193      <table summary="interface - module procedures" width="100%" border="1">
194        <tr>
195          <th colspan="2">Module procedures</th>
196        </tr>
197
198        <tr>
199          <td colspan="2">Place sub-programs in the CONTAINS section of a
200          MODULE. Again, the sub-programs will have automatic interfaces when
201          the MODULE is compiled.  If you give the sub-programs the PUBLIC
202          attribute (which is the default), you will be able to call them from
203          anywhere using the current MODULE. You will also gain all the
204          advantages offered by a MODULE. (E.g. a MODULE will allow you to
205          design your code in a more object-oriented manner.) However, MODULE
206          dependency can have an impact on the efficiency of incremental
207          compilations. For example, if you modify items that are local to the
208          MODULE, it is very difficult for the build system to detect that your
209          change does not affect program units using the MODULE, so the build
210          system will end up compiling the MODULE and all the program units that
211          use it.
212
213            <p>Example:</p>
214          </td>
215        </tr>
216
217        <tr>
218          <td width="50%">In the file "my_mod.f90":
219
220            <pre>
221MODULE my_mod
222! Some module declarations
223CONTAINS
224  SUBROUTINE sub_prog (some, arg)
225  ! Some declarations ...
226  ! Some executable statements ...
227  END SUBROUTINE sub_prog
228END MODULE my_mod
229</pre>
230          </td>
231
232          <td>In the file "foo.f90":
233
234            <pre>
235SUBROUTINE foo (some, arg)
236USE my_mod, ONLY: sub_prog
237! Some declarations ...
238! Some executable statements ...
239CALL sub_prog (some, arg)
240! More executable statements ...
241END SUBROUTINE foo
242</pre>
243          </td>
244        </tr>
245      </table>
246
247      <table summary="interface - interface files" width="100%" border="1">
248        <tr>
249          <th colspan="2">Interface files</th>
250        </tr>
251
252        <tr>
253          <td colspan="2">For each source file containing a standalone
254          SUBROUTINE or FUNCTION, FCM generates a file containing the interface
255          of the SUBROUTINE or FUNCTION. By default, the generated file is named
256          after the original source file, but with the file extension replaced
257          by "*.interface". In the specification section of the caller routine,
258          you will then be able to declare the interface using a Fortran INCLUDE
259          statement to include the interface file. This type of INCLUDE
260          statement is detected automatically by FCM, which will use it to set
261          up the dependency tree.
262       
263            <p>The advantage of using an interface file is that the caller is
264            now dependent on the interface file, rather than the SUBROUTINE or
265            FUNCTION itself. If you change the SUBROUTINE or FUNCTION without
266            modifying its interface, the build system will not re-compile the
267            caller in incremental build, (but it will be intelligent enough to
268            re-link the executable with the updated object).</p>
269
270            <p>Note: By default, an interface file is named after the original
271            source file. Bearing this in mind, it is worth noting that file
272            names in a Unix/Linux system are case-sensitive, and so the
273            interface file name declared by your INCLUDE statement is also case
274            sensitive. If you use an incorrect case in the INCLUDE statement,
275            the dependency tree will be set up incorrectly and the compilation
276            will fail. Another problem is that if you do not name your file
277            after the program unit, the dependency tree will be wrong. To avoid
278            this problem, it is recommended that all source files are named in
279            lower case after the program units they contain. (Alternatively, you
280            can use the TOOL::INTERFACE option in the FCM build configuration
281            file to allow you to alter the default behaviour so that the
282            interface file is named after the "program" unit in lowercase. We
283            may alter FCM in the future so that this will become the default. In
284            the mean time, it is highly recommended that you use this option and
285            design your new code accordingly.)</p>
286
287            <p>Example:</p>
288          </td>
289        </tr>
290
291        <tr>
292          <td width="50%">In the file "sub_prog.f90":
293
294            <pre>
295SUBROUTINE sub_prog (some, arg)
296! Some declarations ...
297! Some executable statements ...
298END SUBROUTINE sub_prog
299</pre>
300          </td>
301
302          <td>In the file "egg.f90":
303
304            <pre>
305SUBROUTINE egg (some, arg)
306! Some declarations ...
307INCLUDE 'sub_prog.interface'
308! More declarations ...
309! Some executable statements ...
310CALL sub_prog (some, arg)
311! More executable statements ...
312END SUBROUTINE egg
313</pre>
314          </td>
315        </tr>
316      </table>
317
318      <table summary="interface - interfaces in a module" width="100%" border="1">
319        <tr>
320          <th colspan="2">Interfaces in a module</th>
321        </tr>
322
323        <tr>
324          <td colspan="2">There is also a half-way house approach between the
325          second and the third options. You can have a dedicated MODULE where a
326          large number of INCLUDE interface file statements are placed. Other
327          program units get their interfaces by importing from this MODULE. A
328          major disadvantage of this approach is that the sub-programs with
329          their interfaces declared within this MODULE will not be able to call
330          any other sub-programs declared within the same MODULE, as it will run
331          into a cyclic dependency problem. Another disadvantage is that if an
332          interface changes, the MODULE and all program units depending on the
333          MODULE will have to be re-compiled, even though the change may be
334          unrelated to some or all of these program units. For these reasons,
335          this approach is only good if you have a bundle of sub-programs that
336          have relatively stable interfaces and are very much independent of one
337          another.
338
339            <p>Note: a similar approach can be useful when you have a library of
340            legacy or external code. In this situation, you will simply declare
341            the interfaces for all the library sub-programs in the MODULE. Any
342            programs that call sub-programs within the library can then import
343            their interfaces by using the MODULE.</p>
344
345            <p>Example:</p>
346          </td>
347        </tr>
348
349        <tr>
350          <td width="50%">In the file "my_i_mod.f90":
351
352            <pre>
353MODULE my_i_mod
354! Some declarations
355INCLUDE 'sub_prog.interface'
356! More declarations
357END MODULE my_i_mod
358</pre>
359          </td>
360
361          <td>In the file "ham.f90":
362
363            <pre>
364SUBROUTINE ham (some, arguments)
365USE my_i_mod, ONLY: sub_prog
366! Some declarations ...
367! Some executable statements ...
368CALL sub_prog (some, arguments)
369! More executable statements ...
370END SUBROUTINE ham
371</pre>
372          </td>
373        </tr>
374      </table>
375
376      <p>FCM also supports the use of a <tt>"! DEPENDS ON"</tt> directive for
377      users to specify a dependency from within a source file. This feature is
378      documented in the <a href=
379      "../user_guide/build.html#advanced_dependency">Further dependency
380      features</a> sub-section of the <a href="../user_guide/">FCM user
381      guide</a>. However, it is worth noting that this method is only included
382      in FCM to support legacy code. It is not a feature recommended for new
383      code, and its use should be gradually phased out from existing code.</p>
384    </li>
385
386    <li>Arguments and local variables should be declared in different
387    statements. It makes your declaration clearer, and it is friendlier to the
388    interface file generator.
389
390      <table summary="declaration example" border="1" width="100%">
391        <tr>
392          <th width="50%">Common practice</th>
393
394          <th>Better approach</th>
395        </tr>
396
397        <tr>
398          <td>
399            <pre>
400SUBROUTINE foo (a, b, c)
401
402INTEGER :: a, b, c, i, j, k
403
404! ...
405
406END SUBROUTINE foo
407</pre>
408          </td>
409
410          <td>
411            <pre>
412SUBROUTINE foo (a, b, c)
413
414INTEGER :: a, b, c
415
416INTEGER :: i, j, k
417
418! ...
419
420END SUBROUTINE foo
421</pre>
422          </td>
423        </tr>
424      </table>
425    </li>
426
427    <li>Use the ONLY clause in a USE &lt;module&gt; statement to declare all
428    imported symbols (i.e. parameters, variables, functions, subroutines, etc).
429    This makes it easier to locate the source of each symbol, and avoids
430    unintentional access to other PUBLIC symbols within the MODULE. It is also
431    friendlier to the compiler and the interface file generator, as they will
432    not have to import modules and symbols that are unnecessary.</li>
433
434    <li>In its default settings, FCM recognises the following file extensions
435    as Fortran free format source files:
436
437      <ul>
438        <li>*.f90, *.f95: regular Fortran free format source files</li>
439
440        <li>*.F90, *.F95: Fortran free format source files that require
441        pre-processing</li>
442
443        <li>*.inc: INCLUDE files that can be added to a regular Fortran free
444        format source file with a Fortran INCLUDE statement</li>
445      </ul>
446    </li>
447  </ol>
448
449  <h3><a name="fcm-cpp"></a>2.2 Use of C pre-processor with Fortran</h3>
450
451  <p>We do not recommend the use of C pre-processor with Fortran. However, it is
452  acknowledged that there are some situations when it is necessary to
453  pre-process Fortran code. FCM supports pre-processing in two ways.
454  Pre-processing can be left to the compiler or it can be done in a separate
455  early stage of the build process. A separate pre-process stage can be useful
456  if pre-processing changes any of the following in a program unit:</p>
457
458  <ul>
459    <li>its name</li>
460
461    <li>its calling interface</li>
462
463    <li>its dependencies</li>
464  </ul>
465
466  <p>However, using a separate pre-process stage is not the best way of working,
467  as it adds an overhead to the build process. If your code requires
468  pre-processing, you should try to design it to avoid changes in the above.</p>
469
470  <p>In practice, the only reasonable use of C pre-processor with Fortran is for
471  code selection. For example, pre-processing is useful for isolating machine
472  specific libraries or instructions, where it may be appropriate to use inline
473  alternatives for small sections of code. Another example is when multiple
474  versions of the same procedure exist in the source tree and you need to use
475  the pre-processor to select the correct version for your build.</p>
476
477  <p>Avoid using the C pre-processor for code inclusion, as you should be able
478  to do the same via the Fortran INCLUDE statement. You should also avoid
479  embedding pre-processor macros within the continuations of a Fortran
480  statement, as it can make your code very confusing.</p>
481
482  <h2><a name="fortran"></a>3. Programming Fortran in general</h2>
483
484  <p>The guidelines in this section are recommended practices for programming
485  Fortran in general. These are guidelines you should try to adhere to when you
486  are developing new code. If you are modifying existing code, you should adhere
487  to its existing standard and style where possible. If you want to change its
488  standard and style, you should seek prior agreements with the owner and the
489  usual developers of the code. Where possible, you should try to maintain the
490  same layout and style within a source file, and preferably, within all the
491  source code in a particular project.</p>
492
493  <p>When reading these guidelines, it is assumed that you already have a good
494  understanding of modern Fortran terminology. It is understood that these
495  guidelines may not cover every aspect of your work. In such cases, you will
496  be a winner if you use a bit of common sense, and always bearing in mind that
497  some other people may have to maintain the code in the future.</p>
498
499  <p>Always test your code before releasing it. Do not ignore compiler warnings,
500  as they may point you to potential problems.</p>
501
502  <h3><a name="fortran-layout"></a>3.1 Layout and formatting</h3>
503
504  <p>The following is a list of recommended practices for layout and formatting
505  when you write code in Fortran.</p>
506
507  <ul>
508    <li>Indent blocks by 2 characters. Where possible, comments should be
509    indented with the code within a block.</li>
510
511    <li>Use space and blank lines where appropriate to format your code to
512    improve readability. (Use genuine spaces but avoid using tabs, as the "tab"
513    character is not in the Fortran character set.) In the following example,
514    the code on the right hand side is preferred:
515
516      <table summary="space example" border="1" width="100%">
517        <tr>
518          <th width="50%">Common practice</th>
519
520          <th>Better approach</th>
521        </tr>
522
523        <tr>
524          <td>
525            <pre>
526DO i=1,n
527  a(i)%c=10*i/n
528  b(i)%d=20+i
529ENDDO
530IF(this==that)THEN
531  distance=0
532  time=0
533ENDIF
534</pre>
535          </td>
536
537          <td>
538            <pre>
539DO i = 1, n
540  a(i) % c = 10 * i / n
541  b(i) % d = 20 + i
542END DO
543
544IF (this == that) THEN
545  distance = 0
546  time     = 0
547END IF
548</pre>
549          </td>
550        </tr>
551      </table>
552    </li>
553
554    <li>Try to confine your line width to 80 characters, so that your code can
555    be printed easily on A4 paper.</li>
556
557    <li>Line up your statements, where appropriate, to improve readability. For
558    example:
559
560      <table summary="line up example" border="1" width="100%">
561        <tr>
562          <th width="50%">Common practice</th>
563
564          <th>Better approach</th>
565        </tr>
566
567        <tr>
568          <td>
569            <pre>
570REAL, INTENT (OUT) :: my_out (:)
571REAL, INTENT (INOUT) :: my_inout (:)
572REAL, INTENT (IN) :: my_in  (:)
573
574! ...
575
576CHARACTER (LEN = 256) :: my_char
577
578my_char = 'This is a very very' // &amp;
579  ' very very very long' // &amp;
580  ' character assignment'.
581</pre>
582          </td>
583
584          <td>
585            <pre>
586REAL, INTENT (  OUT) :: my_out   (:)
587REAL, INTENT (INOUT) :: my_inout (:)
588REAL, INTENT (IN   ) :: my_in    (:)
589
590! ...
591
592CHARACTER (LEN = 256) :: my_char
593
594my_char = 'This is a very very'  // &amp;
595          ' very very very long' // &amp;
596          ' character assignment'.
597</pre>
598          </td>
599        </tr>
600      </table>
601    </li>
602
603    <li>Short and simple Fortran statements are easier to read and understand
604    than long and complex ones. Where possible, avoid using continuation lines
605    in a statement.</li>
606
607    <li>Avoid putting multiple statements on the same line. It is not good for
608    readability.</li>
609  </ul>
610
611  <h3><a name="fortran-style"></a>3.2 Style</h3>
612
613  <p>The following is a list of recommended styles when you write code in
614  Fortran.</p>
615
616  <ul>
617    <li>New code should be written using Fortran 95 syntax. Avoid unportable
618    vendor/compiler extensions. Avoid Fortran 2003 features for the moment, as
619    they will not become widely available in the near future. (Having said that,
620    there is no harm in designing your code with the future in mind. For
621    example, if there is a feature that is not in Fortran 95 and you know that
622    it is in Fortran 2003, you may want to write your Fortran 95 code to make it
623    easier for the future upgrade.)</li>
624
625    <li>Write your program in UK English, unless you have a very good reason for
626    not doing so. Write your comments in simple UK English and name your program
627    units and variables based on sensible UK English words, bearing in mind that
628    your code may be read by people who are not proficient English
629    speakers.</li>
630
631    <li>When naming your variables and program units, always bear in mind that
632    Fortran is a case-insensitive language. (E.g. EditOrExit is the same as
633    EditorExit.)</li>
634
635    <li>Use only characters in the Fortran character set. In particular, accent
636    characters and tabs are not allowed in code, although they are usually OK
637    in comments. If your editor inserts tabs automatically, you should
638    configure it to switch off the functionality when you are editing Fortran
639    source files.</li>
640
641    <li>Although Fortran has no reserved keywords, you should avoid naming your
642    program units and variables with names that match an intrinsic FUNCTION or
643    SUBROUTINE. Similarly, you should avoid naming your program units and
644    variables with names that match a "keyword" in a Fortran statement.</li>
645
646    <li>Be generous with comments. State the reason for doing something,
647    instead of repeating the Fortran logic in words.</li>
648
649    <li>To improve readability, write your program in mainly lower case
650    characters. Writing a program in mainly lower case also means that you will
651    not have to use the Shift/Caps Lock keys often. There is a lot of debate on
652    using upper/lower cases in a case insensitive language such as Fortran.
653    There is no right or wrong, but people have adopted the different approaches
654    over time, each has its own merit. If you are starting a new project, you
655    should choose a suitable option and stick to it. Otherwise, you should stick
656    with the style in the existing code. Some options are listed here:
657
658      <ul>
659        <li>The ALL CAPS Fortran keywords approach, like most of the examples in
660        this document, where all Fortran keywords and intrinsic procedures are
661        written in ALL CAPS. This approach has the advantage that Fortran
662        keywords stand out, but it does increase how often the Shift/Caps Lock
663        key is used. Programmers who are used to some other programming
664        languages may also find it difficult to read a program with a lot of
665        upper case characters.</li>
666
667        <li>The Title Case Fortran keywords approach, where all Fortran keywords
668        are written with an initial capital case letter.</li>
669
670        <li>The sentence case approach, where only the initial character in a
671        Fortran statements is written in capital case letter, like a normal
672        sentence.</li>
673
674        <li>The all lower case approach, where all Fortran keywords are written
675        in lower case letters.</li>
676
677        <li>Some people have also proposed a variable naming convention where
678        local variables start with an initial lower case letter, private
679        module level variables with an initial capital case letter and public
680        module variables written in all caps. However, this approach has been
681        seen by many as too restrictive, and so its use has not been widely
682        spread.</li>
683      </ul>
684    </li>
685
686    <li>Use the new and clearer syntax for LOGICAL comparisons, i.e.:
687
688      <ul>
689        <li>== instead of .EQ.</li>
690
691        <li>/= instead of .NE.</li>
692
693        <li>&gt; instead of .GT.</li>
694
695        <li>&lt; instead of .LT.</li>
696
697        <li>&gt;= instead of .GE.</li>
698
699        <li>&lt;= instead of .LE.</li>
700      </ul>
701    </li>
702
703    <li>Where appropriate, simplify your LOGICAL assignments, for example:
704
705      <table summary="logic assignment example" border="1" width="100%">
706        <tr>
707          <th width="50%">Common practice</th>
708
709          <th>Better approach</th>
710        </tr>
711
712        <tr>
713          <td>
714            <pre>
715IF (my_var == some_value) THEN
716  something      = .TRUE.
717  something_else = .FALSE.
718
719ELSE
720  something      = .FALSE.
721  something_else = .TRUE.
722END IF
723
724IF (something .EQV. .TRUE.) THEN
725  CALL do_something ()
726  ! ...
727END IF
728</pre>
729          </td>
730
731          <td>
732            <pre>
733something      = (my_var == some_value)
734something_else = (my_var /= some_value)
735
736IF (something) THEN
737  CALL do_something ()
738  ! ...
739END IF
740</pre>
741          </td>
742        </tr>
743      </table>
744    </li>
745
746    <li>Positive logic is usually easier to understand. When you have an
747    IF-ELSE-END IF construct, you should use positive logic in the IF test,
748    provided that the positive and the negative blocks are about the same size.
749    (However, it may be more appropriate to use negative logic if the negative
750    block is significantly bigger than the positive block.) For example:
751
752      <table summary="positive logic example" border="1" width="100%">
753        <tr>
754          <th width="50%">Common practice</th>
755
756          <th>Better approach</th>
757        </tr>
758
759        <tr>
760          <td>
761            <pre>
762IF (my_var != some_value) THEN
763  CALL do_this ()
764
765ELSE
766  CALL do_that ()
767END IF
768</pre>
769          </td>
770
771          <td>
772            <pre>
773IF (my_var == some_value) THEN
774  CALL do_that ()
775
776ELSE
777  CALL do_this ()
778END IF
779</pre>
780          </td>
781        </tr>
782      </table>
783    </li>
784
785    <li>To improve readability, you should always use the optional space to
786    separate the following Fortran keywords:
787
788      <table summary="space in Fortran keywords" width="100%">
789        <tr class="mono">
790          <td width="25%">else if</td>
791
792          <td width="25%">end do</td>
793
794          <td width="25%">end forall</td>
795
796          <td width="25%">end function</td>
797        </tr>
798
799        <tr class="mono">
800          <td width="25%">end if</td>
801
802          <td width="25%">end interface</td>
803
804          <td width="25%">end module</td>
805
806          <td width="25%">end program</td>
807        </tr>
808
809        <tr class="mono">
810          <td width="25%">end select</td>
811
812          <td width="25%">end subroutine</td>
813
814          <td width="25%">end type</td>
815
816          <td width="25%">end where</td>
817        </tr>
818
819        <tr class="mono">
820          <td width="25%">select case</td>
821
822          <td width="25%">-</td>
823
824          <td width="25%">-</td>
825
826          <td width="25%">-</td>
827        </tr>
828      </table>
829    </li>
830
831    <li>If you have a large or complex code block embedding other code blocks,
832    you may consider naming some or all of them to improve readability.</li>
833
834    <li>If you have a large or complex interface block or if you have one or
835    more sub-program units in the CONTAINS section, you can improve readability
836    by using the full version of the END statement (i.e. END SUBROUTINE
837    &lt;name&gt; or END FUNCTION &lt;name&gt; instead of just END) at the end of
838    each sub-program unit. For readability in general, the full version of the
839    END statement is recommended over the simple END.</li>
840
841    <li>Where possible, consider using CYCLE, EXIT or a WHERE-construct to
842    simplify complicated DO-loops.</li>
843
844    <li>When writing a REAL literal with an integer value, put a 0 after the
845    decimal point (i.e. 1.0 as opposed to 1.) to improve readability.</li>
846
847    <li>Where reasonable and sensible to do so, you should try to match the
848    names of dummy and actual arguments to a SUBROUTINE/FUNCTION.</li>
849
850    <li>In an array assignment, it is recommended that you use array notations
851    to improve readability. E.g.:
852
853      <table summary="array notation example" border="1" width="100%">
854        <tr>
855          <th width="50%">Common practice</th>
856
857          <th>Better approach</th>
858        </tr>
859
860        <tr>
861          <td>
862            <pre>
863INTEGER :: array1(10, 20), array2(10, 20)
864INTEGER :: scalar
865
866array1 = 1
867array2 = array1 * scalar
868</pre>
869          </td>
870
871          <td>
872            <pre>
873INTEGER :: array1(10, 20), array2(10, 20)
874INTEGER :: scalar
875
876array1(:, :) = 1
877array2(:, :) = array1(:, :) * scalar
878</pre>
879          </td>
880        </tr>
881      </table>
882    </li>
883
884    <li>Where appropriate, use parentheses to improve readability. E.g.:
885
886      <table summary="parentheses example" border="1" width="100%">
887        <tr>
888          <th width="50%">Common practice</th>
889
890          <th>Better approach</th>
891        </tr>
892
893        <tr>
894          <td>
895            <pre>
896a = b * i + c / n
897</pre>
898          </td>
899
900          <td>
901            <pre>
902a = (b * i) + (c / n)
903</pre>
904          </td>
905        </tr>
906      </table>
907    </li>
908  </ul>
909
910  <h3><a name="fortran-feature"></a>3.3 Fortran features</h3>
911
912  <p>The following is a list of Fortran features that you should use or
913  avoid.</p>
914
915  <ul>
916    <li>Use IMPLICIT NONE in all program units. It means that you have declare
917    all your variables explicitly. This helps to reduce bugs in your program
918    that will otherwise be difficult to track.</li>
919
920    <li>Design your derived data types carefully and use them to group related
921    variables. Appropriate use of derived data types will allow you to design
922    modules and procedures with simpler and cleaner interfaces.</li>
923
924    <li>Where possible, module variables and procedures should be declared
925    PRIVATE. This avoids unnecessary export of symbols, promotes data hiding and
926    may also help the compiler to optimise the code.</li>
927
928    <li>When you are passing an array argument to a SUBROUTINE/FUNCTION, and the
929    SUBROUTINE/FUNCTION does not change the SIZE/DIMENSION of the array, you
930    should pass it as an assumed shape array. Memory management of such an array
931    is automatically handled by the SUBROUTINE/FUNCTION, and you do not have to
932    worry about having to ALLOCATE or DEALLOCATE your array. It also helps the
933    compiler to optimise the code.</li>
934
935    <li>Use an array POINTER when you are passing an array argument to a
936    SUBROUTINE, and the SUBROUTINE has to alter the SIZE/DIMENSION of the array.
937    You should also use an array POINTER when you need a dynamic array in a
938    component of a derived data type. (Note: Fortran 2003 allows passing
939    ALLOCATABLE arrays as arguments as well as using ALLOCATABLE arrays as
940    components of a derived data type. Therefore, the need for using an array
941    POINTER should be reduced once Fortran 2003 becomes more widely
942    accepted.)</li>
943
944    <li>Where possible, an ALLOCATE statement for an ALLOCATABLE array (or a
945    POINTER used as a dynamic array) should be coupled with a DEALLOCATE within
946    the same scope. If an ALLOCATABLE array is a PUBLIC MODULE variable, it is
947    highly desirable if its memory allocation and deallocation are only
948    performed in procedures within the MODULE in which it is declared. You may
949    consider writing specific SUBROUTINEs within the MODULE to handle these
950    memory managements.</li>
951
952    <li>To avoid memory fragmentation, it is desirable to DEALLOCATE in reverse
953    order of ALLOCATE.
954
955      <table summary="ALLOCATE example" border="1" width="100%">
956        <tr>
957          <th width="50%">Common practice</th>
958
959          <th>Better approach</th>
960        </tr>
961
962        <tr>
963          <td>
964            <pre>
965ALLOCATE (a(n))
966ALLOCATE (b(n))
967ALLOCATE (c(n))
968! ... do something ...
969DEALLOCATE (a)
970DEALLOCATE (b)
971DEALLOCATE (c)
972</pre>
973          </td>
974
975          <td>
976            <pre>
977ALLOCATE (a(n))
978ALLOCATE (b(n))
979ALLOCATE (c(n))
980! ... do something ...
981DEALLOCATE (c)
982DEALLOCATE (b)
983DEALLOCATE (a)
984</pre>
985          </td>
986        </tr>
987      </table>
988    </li>
989
990    <li>Always define a POINTER before using it. You can define a POINTER in its
991    declaration by pointing it to the intrinsic function NULL (). Alternatively,
992    you can make sure that your POINTER is defined or nullified early on in the
993    program unit. Similarly, NULLIFY a POINTER when it is no longer in use,
994    either by using the NULLIFY statement or by pointing your POINTER to NULL
995    ().</li>
996
997    <li>Avoid the DIMENSION attribute or statement. Declare the DIMENSION with
998    the declared variables. E.g.:
999
1000      <table summary="dimension attribute example" border="1" width="100%">
1001        <tr>
1002          <th width="50%">Common practice</th>
1003
1004          <th>Better approach</th>
1005        </tr>
1006
1007        <tr>
1008          <td>
1009            <pre>
1010INTEGER, DIMENSION(10) :: array1
1011INTEGER                :: array2
1012DIMENSION              :: array2(20)
1013</pre>
1014          </td>
1015
1016          <td>
1017            <pre>
1018INTEGER :: array1(10), array2(20)
1019</pre>
1020          </td>
1021        </tr>
1022      </table>
1023    </li>
1024
1025    <li>Avoid COMMON blocks and BLOCK DATA program units. Use PUBLIC MODULE
1026    variables.</li>
1027
1028    <li>Avoid the EQUIVALENCE statament. Use a POINTER or a derived data type,
1029    and the TRANSFER intrinsic function to convert between types.</li>
1030
1031    <li>Avoid the PAUSE statement, as your program will hang in a batch
1032    environment. If you need to halt your program for interactive use, consider
1033    using a READ* statement instead.</li>
1034
1035    <li>Avoid the ENTRY statement. Use a MODULE or internal SUBROUTINE.</li>
1036
1037    <li>Avoid the GOTO statement. The only commonly acceptable usage of GOTO is
1038    for error trapping. In such case, the jump should be to a commented 9999
1039    CONTINUE statement near the end of the program unit. Typically, you will
1040    only find error handlers beyond the 9999 CONTINUE statement.</li>
1041
1042    <li>Avoid assigned GOTO, arithmetic IF, etc. Use the appropriate modern
1043    constructs such as IF, WHERE, SELECT CASE, etc..</li>
1044
1045    <li>Avoid numbered statement labels. DO ... <em>label</em> CONTINUE
1046    constructs should be replaced by DO ... END DO constructs. FORMAT statements
1047    should be replaced by format strings. (Tip: a format string can be a
1048    CHARACTER variable.)</li>
1049
1050    <li>A FUNCTION should be PURE, i.e. it should have no side effects (e.g.
1051    altering an argument or module variable, or performing I/O). If you need to
1052    perform a task with side effects, you should use a SUBROUTINE instead.</li>
1053
1054    <li>Avoid using a statement FUNCTION. Use an internal FUNCTION instead.</li>
1055
1056    <li>Avoid RECURSIVE procedures if possible. RECURSIVE procedures are usually
1057    difficult to understand, and are always difficult to optimise in a
1058    supercomputer environment.</li>
1059
1060    <li>Avoid using the specific names of intrinsic procedures. Use the generic
1061    names of intrinsic procedures where possible.</li>
1062  </ul>
1063
1064  <h2><a name="template"></a>4. Program templates</h2>
1065
1066  <p>The following is a basic template for a SUBROUTINE:</p>
1067  <pre>
1068SUBROUTINE &lt;subroutine_name&gt; (&lt;arguments&gt;, ...)
1069
1070! Description:
1071!   &lt;Explain the usage of the subroutine and what it does.&gt;
1072!
1073! (c) Crown copyright Met Office. All rights reserved.
1074! For further details please refer to the file COPYRIGHT.txt
1075! which you should have received as part of this distribution.
1076! ------------------------------------------------------------------------------
1077
1078! Modules
1079&lt;module declarations, each with a list of imported symbols&gt;
1080
1081IMPLICIT NONE
1082
1083! Arguments:
1084&lt;arguments with INTENT (  OUT)&gt;
1085&lt;arguments with INTENT (INOUT)&gt;
1086&lt;arguments with INTENT (IN   )&gt;
1087
1088! Local declarations:
1089&lt;parameters, derived data types, variables, etc&gt;
1090
1091! INTERFACE blocks
1092&lt;INCLUDE interface blocks for external procedures&gt;
1093&lt;interface blocks for procedure and operator overloading&gt;
1094
1095!-------------------------------------------------------------------------------
1096
1097&lt;... subroutine executable statements&gt;
1098
1099!-------------------------------------------------------------------------------
1100
1101CONTAINS
1102
1103  &lt;sub-programs&gt;
1104
1105END SUBROUTINE &lt;subroutine_name&gt;
1106</pre>
1107
1108  <p>Note:</p>
1109
1110  <ul>
1111    <li>The basic templates for other types of program units are similar to
1112    that of a SUBROUTINE, with the following exceptions:
1113
1114      <ul>
1115        <li>A PROGRAM does not have arguments, so the "arguments" list in the
1116        header and the "Arguments" section in the declaration section should be
1117        removed. All declarations are local to a PROGRAM, so the "Local
1118        Declarations" section should be replaced by a simple "Declarations"
1119        section.</li>
1120
1121        <li>A FUNCTION should have no INTENT (OUT) and INTENT (INOUT) arguments.
1122        You will also need to declare the type returned by the FUNCTION. This
1123        can be in the FUNCTION header, declared separately or declared using a
1124        RESULT clause. For the latters, make your declaration at the beginning
1125        of the "Local declarations" section.</li>
1126
1127        <li>A MODULE does not have arguments, so the "arguments" list in the
1128        header and the "Arguments" section in the declaration section should be
1129        removed. Where appropriate, the "Local Declarations" section should be
1130        replaced by a "PUBLIC declarations" section and a "PRIVATE declarations"
1131        section.</li>
1132      </ul>
1133    </li>
1134
1135    <li>When you are distributing your code, you should include a COPYRIGHT.txt
1136    file at a top level directory in your source tree. The file should contain
1137    the detailed copyright information:
1138
1139      <ul>
1140        <li>the copyright year, ranging from the year the code is first
1141        distributed to the year the code is last distributed</li>
1142
1143        <li>the copyright statement</li>
1144
1145        <li>the owner of the code and his/her address</li>
1146      </ul>
1147
1148      <p>For example:</p>
1149      <pre>
1150!------------------------------------------------------------------------------!
1151!                                                                              !
1152! (C) Crown copyright 2005-6 Met Office. All rights reserved.                  !
1153!                                                                              !
1154! Use, duplication or disclosure of this code is subject to the restrictions   !
1155! as set forth in the contract. If no contract has been raised with this copy  !
1156! of the code, the use, duplication or disclosure of it is strictly            !
1157! prohibited. Permission to do so must first be obtained in writing from the   !
1158! Head of Numerical Modelling at the following address:                        !
1159!                                                                              !
1160! Met Office, FitzRoy Road, Exeter, Devon, EX1 3PB, United Kingdom             !
1161!                                                                              !
1162!------------------------------------------------------------------------------!
1163</pre>
1164    </li>
1165  </ul>
1166 
1167  <script type="text/javascript" src="maintain.js"></script>
1168</body>
1169</html>
Note: See TracBrowser for help on using the repository browser.