Legacy FORTRAN 77 & Modernization

You will meet old code.

You will meet old code. Know the features — and their modern replacements.

column rules, 72-char limit typos become variables implicit none COMMON blocks global, untyped shared storage allocatables, transfer, pointers

GOTO, computed/assigned GOTO, arithmetic IF if, select case, do, exit, cycle DO 10 I=1,N... 10 CONTINUE do... end do REAL*8, INTEGER*4 real(real64), integer(int32) DOUBLE PRECISION ENTRY statements multiple entry points INCLUDE files for declarations DATA statements Hollerith constants 5HHELLO PAUSE, alternate RETURN normal control flow for COMMON init Assumed-size arrays A(*) assumed-shape A(:) SAVE everywhere / static locals explicit state, derived types

21.1 A FORTRAN 77 example and its modern version

C     LEGACY FIXED-FORM
      PROGRAM SUMSQ
      INTEGER I, N
      REAL S
      PARAMETER (N=10)
      S = 0.0
      DO 10 I = 1, N
         S = S + I**2
   10 CONTINUE
      WRITE(6,100) S
  100 FORMAT(' SUM = ', F10.2)
      END
! MODERN FREE-FORM
program sumsq
  implicit none
  integer, parameter :: n = 10
  integer :: i
  print '(a, f10.2)', 'SUM = ', real(sum([(i**2, i = 1, n)]))
end program sumsq

21.2 Modernization workflow

Get it compiling and add regression tests (capture current outputs).

Convert to free form (tools: findent, fprettify, to_f90, LFortran/plusFORT/SPAG, fortran-legacy-tools).

Add implicit none everywhere; fix the resulting errors.

Wrap procedures in modules (gains interface checking).

Replace COMMON with module data, then with derived types passed as arguments.

Replace GOTO with structured constructs.

Introduce kinds, intents, allocatables.

Refactor incrementally, re-running tests after each step.

🧪 Part II Exercises

Write a program that reads an unknown number of values from a file into an allocatable array (growing it), then prints statistics.

Implement matrix multiplication with triple loops; compare against matmul for correctness and speed (try both loop orders).

Write an elemental function relu(x) and a pure function softmax(x) working on arrays.

Create a module string_utils with to_upper, to_lower, split, replace, and count_words.

Write a generic numerical integrator taking a procedure argument; integrate several functions with trapezoid and Simpson rules.

Define a student derived type (name, ID, grades array); read a CSV of students and print averages sorted by grade.

Implement a singly linked list with insert, delete, search, and free; check for leaks with Valgrind or -fsanitize=address.

Write and read a 1000×1000 matrix in both formatted and stream unformatted form; compare file sizes and times.

Use a NAMELIST input file to configure a simple simulation (projectile motion) and write results to CSV.

Take a provided FORTRAN 77 subroutine (with COMMON and GOTO) and modernize it into a module procedure with tests.