Chapter 2. Writing reusable code with functions and subroutines

 

Chapter 3 from Modern Fortran by Milan Curcic

This chapter covers:

  • What are procedures and why use them
  • Two kinds of procedures: Functions and subroutines
  • Writing procedures that make no side-effects
  • Writing procedures that work on both scalars and arrays

In the previous chapter, you learned about the core elements of Fortran: declaration of scalar and array variables, do-loops to iterate parts of the code for a desired number of times, and arithmetic expressions and assignments. We used them to write a simple simulator that predicts the motion of an object in space and time due to background flow. As we learn new Fortran features, we’ll continuously expand and improve our app to produce more realistic simulations. This chapter introduces functions and subroutines, which will help us manage the complexity of our growing app.

3.1  Toward higher app complexity

3.2  Don’t repeat yourself, use procedures

3.3  Modifying program state with subroutines

3.4  Writing pure procedures to avoid side effects

3.5  Writing procedures that operate on both scalars and arrays

3.6  Procedures with optional arguments

3.7  Tsunami simulator: Putting it all together

3.8  Answer key

3.9  New Fortran elements, at a glance

3.10  Further reading

3.11  Summary