source: OFFICIAL/FCM_V1.3/doc/standards/fortran_standard.html @ 12

Last change on this file since 12 was 1, checked in by fcm, 15 years ago

creation de larborescence

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