New URL for NEMO forge!   http://forge.nemo-ocean.eu

Since March 2022 along with NEMO 4.2 release, the code development moved to a self-hosted GitLab.
This present forge is now archived and remained online for history.
fortran_standard.html in vendors/fcm/current/doc/standards – NEMO

source: vendors/fcm/current/doc/standards/fortran_standard.html @ 1980

Last change on this file since 1980 was 1980, checked in by flavoni, 14 years ago

importing fcm vendor

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