Fortran

Guide To Learn

An overview of Fortran program units

When I introduced program as the main Fortran program unit in the previous chapter, I also mentioned a few others: functions, subroutines, and modules. Functions and subroutines, which are the focus of this chapter, are both kinds of procedures. A procedure is a miniprogram that can be called any number of times from the main program, or from another procedure. Like the main program, procedures have executable code, the code that does things. Figure 3.5 illustrates functions and subroutines.

Figure 3.5 Overview of a function and a subroutine, and how they’re invoked from the main program

Each of these units has different properties and a unique purpose:

  • Main program –Every Fortran application must have one, and only one, main program. The main program can contain declarative and executable code, as well as definitions of procedures. The main program is the only program unit that you can invoke as its own executable program.
  • Function –A function is a kind of procedure. Like the main program, it can contain declarative and executable code, but you can’t invoke it on its own, and you can only call it from the main program or another procedure. A function always returns only one variable as a result and can only be invoked in expressions. Functions are thus best suited for minimal computational tasks that don’t cause side effects.
  • Subroutine –A subroutine is another kind of procedure. In many respects, it’s similar to a function, with two notable differences:
    1. You can’t use a subroutine in expressions, and you have to call it using a dedicated call statement.
    2. A subroutine can return any number of results in the argument list. Subroutines are better suited for work that modifies program state or has other side effects, such as input or output.

For short and simple applications, using only the main program does the job. Once you start repeating code, it may be time to define it in a function and call it from the main program. Functions are powerful because you can use them in expressions, and they’re especially well suited for writing pure, side effect-free code. Subroutines are appropriate when side effects are inevitable–for example, for I/O or when working with shared, globally accessible data. Figure 3.6 illustrates how you can define and call functions and subroutines in the main program.

Figure 3.6 Defining and accessing an external function and subroutine in the main program

Overall, these are general rules of thumb as best practice, and not hard rules. You’ll discover the best way to use functions and subroutines yourself by applying them in practice.

An overview of Fortran program units

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top