Tips index#

By topic#

According to the FortranTip topics page. Note that these are exclusive categories.

Allocation#

  • 012. Fortran has allocation-on-assignment

  • 040. If allocation errors must be handled, use allocatable rather than automatic arrays in procedures

  • 180. ALLOCATE with SOURCE or MOLD to set values or SHAPE.

  • 182. ALLOCATE has an optional ERRMSG specifier.

  • 183. If unsure, test whether a variable is ALLOCATED before using DEALLOCATE.

  • 184. Use MOVE_ALLOC to resize an array.

  • 185. MOVE_ALLOC may be faster than RESHAPE or allocation on assignment to resize an array.

Array arguments#

  • 122. Array lower bounds are not preserved when passed as assumed shape argument.

  • 123. Bounds of a derived type array component are preserved when passed to procedure.

  • 124. Bounds of an allocatable array are preserved when passed to an allocatable, intent(in) or intent(in out) argument.

  • 136. Check that assumed-shape array arguments have consistent dimensions.

  • 226. Wrap a procedure with explicit shape array arguments in a procedure with an assumed shape arguments for safety.

  • 227. Sequence association effectively lets you pass a pointer to an array element.

  • 228. With sequence association, the shapes of the actual and dummy arguments need not match.

Arrays#

  • 008. Array intrinsic functions: sum, minval, maxval, minloc, findloc

  • 009. Fortran array sections contain both endpoints

  • 010. Fortran arrays can have any lower bound (the default is 1)

  • 011. sum and other array functions have an optional dimension argument

  • 021. pack selects elements

  • 042. Zero-size array constructor

  • 043. Comparing Fortran and NumPy syntax

  • 047. reshape with the optional order and pad arguments

  • 049. Fortran is column-major

  • 053. Use ALL(A==B) to test for array equality

  • 060. Many compilers evaluate ALL(x==y) efficiently with short-circuiting

  • 073. Use parameters to dimension fixed-size arrays to make a code easier to change

  • 084. DIMENSION can be used to declare several arrays of the same SHAPE

  • 095. Array constructor with [] was introduced in Fortran 2003. Still valid is (//)

  • 108. Vector subscript can be used for non-contiguous array sections.

  • 109. Setting the values of an array section

  • 116. Concatenate arrays and scalars in an array constructor []

  • 117. spread(source, dim, ncopies) copies a SOURCE array NCOPIES times along dimension DIM.

  • 121. How to reverse an array or character string

  • 229. Use the optional KIND argument of SIZE, MINLOC, FINDLOC etc. for large arrays.

Associate#

  • 019. associate creates an alias for expressions or variables

  • 141. Pointer assignment and ASSOCIATE can create shallow copies.

  • 142. ASSOCIATE is preferred over POINTER to create an alias because POINTER can inhibit optimization.

  • 143. ASSOCIATE statement can set several independent variables.

  • 144. A variable ASSOCIATEd to an ALLOCATABLE variable is not ALLOCATABLE.

  • 146. Bounds of associate-name for whole array or array section selector

  • 181. ASSOCIATE to an array-valued expression allocates an array.

Basics#

  • 001. Hello World

  • 006. ** is the exponentiation operator

  • 007. Integer division truncates

  • 054. Consider using a tolerance to compare floats

  • 064. Case insensitivity

  • 077. Use integer powers when possible.

  • 078. Parenthesize a variable to copy it “on the fly”.

  • 135. ERROR STOP vs. STOP.

  • 139. BLOCK construct allows declarations after executable statements.

Character variables#

  • 016. An array of character variables has elements of the same length

  • 017. Character variables are padded with spaces at the end if necessary

  • 051. Doubled delimiter in a string is regarded as a single character of the constant

  • 059. LEN of a character variable may be deferred in Fortran 2003 on

  • 066. Do case-insensitive string comparisons by converting to lower case

  • 079. Substrings of character variable arrays

  • 080. Intrinsic character functions

  • 081. Syntax for character array without manual padding

  • 118. Convert from strings to numbers and the reverse using internal READ and WRITE.

  • 119. Internal write to character variable too small to hold output causes run-time error.

  • 120. Character variables can be compared like numerical variables.

  • 169. print*,char(7) causes the program to beep.

  • 170. Use an implied do loop with TRIM to print an array of character variables without trailing blanks.

Compiling#

  • 197. Create an executable in one step by compiling all source files or by compiling source files with -c and linking the object files.

  • 198. Compilation can fail if there is no main program or if a USEd module has not been compiled.

  • 199. Fortran Package Manager simplifies building programs.

  • 200. Fortran-lang has a section on Building Programs, and F18 has a compiler options comparison.

  • 201. Compiler Explorer shows the assembly code generated by many Fortran compilers.

  • 202. Compilers may accept extensions by default but have options to flag non-standard code.

  • 203. Use ifort -fast or gfortran -O3 -march=native for speed.

  • 204. When is the -ffast-math option safe?

  • 207. Use compiler options to catch the use of uninitialized variables.

Conditionals#

  • 014. if-else if-end if block

  • 015. merge(x, y, cond)

  • 018. Fortran has a one-line if

  • 035. select case for conditional execution

  • 055. ANY and ALL may not be the most efficient methods to compare arrays.

  • 056. Standards committee has approved conditional expressions

Data types#

  • 002. Intrinsic data types

  • 033. Declare floating point variables with kinds

  • 034. Replace non-standard REAL*8 declaration with real(kind=real64)

  • 048. cmplx should be used with a kind argument

  • 057. Use .true. and .false. for Booleans, not 1 and 0

  • 070. Real and integer KIND constants from iso_fortran_env; HUGE() and TINY()

  • 071. KindFinder code finds all KIND Values implemented by a compiler

  • 072. Fortran 2008 introduced z%re and z%im as alternatives to real(z) and aimag(z)

  • 075. KIND numbers of types are not portable across compilers and should not be used directly.

  • 076. Use d0 or _kind to make a constant double precision.

  • 130. storage_size(A) returns the storage size of argument A in bits.

  • 195. TRANSFER can be used to store one type in another type.

  • 196. NOT, IAND, IOR, and IEOR perform logical operations on the bit representations of integers.

  • 205. Use IANY instead of nested IOR, IALL instead of nested IAND.

  • 206. B, O, Z edit descriptors can be used to print integers as binary, octal, or hexadecimal.

  • 224. Ways of declaring character variables

Derived types#

  • 045. Derived type definition, initialization, and operator overloading

  • 050. Store data as an array of derived types or a derived type with array components?

  • 126. A derived type can be used where a scalar is needed.

  • 127. A derived type can have derived type components.

  • 128. A derived type component can have a default value.

  • 129. A derived type can have PRIVATE components.

  • 186. Deallocating a derived type deallocates its allocatable components.

  • 191. Derived type array sections are allowed before or after the % component selector, but not in both places.

  • 192. Implied do loop can access arbitrary derived type array sections.

  • 194. Use PACK to select records from an array of derived types.

Environment variables#

  • 111. Execute_command_line() to pass a command to the shell.

  • 112. Execute_command_line() can call gnuplot to display a plot during a run.

  • 113. Document results with compiler_version(), compiler_options(), and other intrinsics.

  • 114. Demonstrate subroutine get_environment_variable(name,value) of Fortran 2003.

  • 115. get_command() and get_command_argument() get command line arguments.

Floating point arithmetic#

  • 103. IEEE_ARITHMETIC module has functions to test numerical conditions.

  • 104. Call ieee_set_halting_mode() to set floating point conditions that halt program.

Fortran resources#

  • 005. Fortran compilers and tutorials

  • 052. Intel Fortran Compiler (ifx)

  • 058. To learn about Fortran beyond F95, read the New Features articles of John Reid

  • 061. Compiler Support for the Fortran 2008 and 2018 Standards

  • 065. Fortran-lang suggested variable naming conventions

  • 092. List of Fortran compilers, build tools, text editors, etc.

  • 106. Google foo filetype:f90 or foo filetype:f to find Fortran code with foo.

  • 107. Polyhedron suggested compiler optimization options and Fortran 95 benchmarks

  • 110. Mistakes in Fortran 90 Programs That Might Surprise You, by Szymanski

  • 125. Modern Fortran Reference Card and Quick Reference/Cheat Sheet.

  • 138. Five free C C++ Fortran compiler families

  • 173. MOOC on “Defensive programming and debugging”

  • 193. Fortran codes are listed by topic at the fortran-lang package index and Fortran Code on GitHub

  • 219. Use valgrind to find memory leaks in programs that use pointers.

  • 223. List of books with Fortran code other than Fortran textbooks.

Generic programming#

  • 132. Unlimited polymorphic allocatable variable can be set to any type.

  • 133. Unlimited polymorphic pointer can point to any type.

  • 134. Assumed type arguments have no declared type.

Input and Output#

  • 036. Reading user input

  • 037. Using read and write for file I/O

  • 038. Use unformatted stream of Fortran 2003 for large-scale I/O

  • 041. Use g0.d and : edit descriptors with infinite repeat count to write delimited (CSV, etc.) output

  • 044. List-directed vs. explicitly formatted output

  • 069. Advance=”no” specifier of WRITE

  • 091. Use iostat and iomsg to handle READ errors

  • 150. Connect INPUT_UNIT and OUTPUT_UNIT to files to redirect standard input and output.

  • 151. Unit n is connected to fort.n by default for most compilers.

  • 152. Write to many files by creating file names with internal write.

  • 153. Number of files open simultaneously is limited, so they should be closed when possible.

  • 154. Use NEWUNIT in OPEN to get an unused unit number.

  • 155. Use INQUIRE to get unit and file properties.

  • 156. How to append to a file or delete it

  • 157. DIRECT access file allows access to arbitrary record without looping over the previous records.

  • 158. Specific array elements can read or written to unformatted stream file by specifying the POS.

  • 159. Stream input/output article by Clive Page

  • 160. Slash / terminates a record.

  • 161. Use REWIND and BACKSPACE to change file position.

  • 171. Error in READ statement causes all variables to become undefined.

  • 172. Use the “(a)” format to read a line of a file into a string.

  • 174. List-directed READ will use several lines if necessary.

  • 175. Use an implied do loop with a dummy variable to skip fields when reading a file.

  • 176. Because recursive I/O is prohibited, a function should use ERROR STOP msg instead of PRINT statements for error messages.

  • 177. Read a file into a string with unformatted stream.

  • 178. Scratch files are unnamed temporary files for I/O.

  • 190. Serialize a derived type using unformatted stream I/O.

  • 225. Special meanings of * and / in list-directed input

Interoperability with C and C++#

  • 208. Fortran 2003 standardized the interoperation of Fortran and C.

  • 209. C library functions can be called if an INTERFACE is provided.

  • 210. Non-pointer arguments of C functions should have the VALUE attribute in the Fortran interface.

  • 211. A simple derived type with the BIND(C) attribute interoperates with a C struct.

  • 212. The Fortran name can differ from the C name of a function if the NAME attribute appears in BIND.

  • 213. C++ functions can be called from Fortran if they are declared extern “C” and have C-like arguments.

  • 214. Use the std::span container from C++ 20 to view a contiguous Fortran array with a STL-compatible interface.

  • 215. Fortran array x(n1,n2) passed to C array x[n2][n1]

  • 216. Common block and module variables with bind(c) can be accessed from C.

  • 217. An allocated allocatable array can be passed to C as an explicit-shape array.

  • 218. Use TYPE(C_PTR) and C_F_POINTER to call a C function returning a pointer.

  • 220. Use c_funloc() to pass a Fortran function as an argument to a C function.

  • 221. An omitted Fortran optional argument corresponds to a NULL argument of a C function.

  • 222. C can call Fortran procedures with prototypes generated by gfortran -fc-prototypes.

Loops#

  • 003. do loop

  • 004. exiting a do loop

  • 020. Loop variable after completion

  • 162. EXIT can be used to leave a named outer loop.

  • 163. CYCLE skips the remaining statements in a loop.

  • 164. Changing a loop index within a loop is invalid.

  • 165. Number of iterations in a loop is determined at the beginning.

  • 166. Beware of a loop to huge(i), since huge(i)+1 is out of range.

  • 167. Invalid loop bounds were discussed at Fortran Discourse.

  • 168. DO WHILE loop iterates as long as condition at beginning is met.

Math intrinsic functions#

  • 046. Use GAMMA to compute factorials

  • 062. MODULO vs. MOD function

Modules#

  • 025. Avoid polluting the namespace by using use-only

  • 026. Function overloading using an interface with module procedures

  • 032. Use parameters in modules to define constants

  • 039. Name modules and the source files containing them consistently, with one module per file

  • 087. Use the same name for analogous procedures defined in different modules using an INTERFACE

  • 088. How to rename an imported module entity

  • 089. Module entities are PUBLIC by default.

  • 090. An unqualified USE foo statement imports public entities defined in foo and what foo imported.

  • 096. PROTECTED module variables cannot be changed outside the module.

  • 179. Place IMPLICIT NONE before CONTAINS in a module.

Parameterized derived types#

  • 187. Links to tutorials on parameterized derived types (PDT).

  • 188. PDT can have array dimension, KIND, and character LEN parameters.

  • 189. PDT can have fixed parameters at compile time or be ALLOCATABLE.

Pointers#

  • 147. Pointer can remap array shape and bounds.

  • 148. Pointer should be initialized to null() to avoid undefined association status.

  • 149. Use ALLOCATABLE arrays or ASSOCIATE instead of POINTER when possible.

Procedures#

  • 022. Functions should be pure and have intent(in) arguments

  • 023. elemental functions broadcast arguments

  • 024. Put functions and subroutines in modules to ensure that interfaces are checked

  • 027. Optional arguments (and the random_number intrinsic)

  • 028. Define and call a subroutine

  • 029. Subroutines can have intent(in out) arguments, but functions should not

  • 030. Specify function and subroutine intents

  • 031. Procedures can be recursive

  • 063. Returning multiple values from a subroutine or function

  • 067. How size of an array function result can depend on function arguments

  • 068. Len of character variable function result can depend on arguments

  • 074. Avoid implicit save

  • 082. Two types of syntax for defining a function

  • 083. Propagation of an optional argument

  • 085. UnALLOCATED variable passed to a procedure is not PRESENT there.

  • 086. Procedures can be called with a mix of named and positional arguments.

  • 093. Fortran 2008 introduced IMPURE ELEMENTAL procedures

  • 094. Impure elemental procedure can be used to generate array of non-uniform variates

  • 097. Use INTRINSIC to specify that compiler-provided procedures and modules are referenced

  • 098. VALUE attribute for procedure arguments introduced in Fortran 2003

  • 100. An INTENT(OUT) argument is undefined at the beginning of a procedure

  • 101. ALLOCATABLE INTENT(OUT) argument is deallocated.

  • 102. Dummy argument that is changed must be definable in the caller.

  • 105. A procedure can have an argument that is another PROCEDURE with an INTERFACE.

  • 131. Fortran 2018 procedures can have assumed-rank arguments.

  • 137. Errors in a procedure can be handled with an optional argument.

  • 140. Internal procedures have access to variables from the host unless they are overridden by local variables.

Style#

  • 013. New Fortran code should use free source form and .f90 suffix

  • 099. Turn compiler warnings into errors to force code defects to be fixed.