concept subroutine in category fortran

appears as: subroutines, subroutine, subroutine, A subroutine, The subroutine
Modern Fortran: Building efficient parallel applications MEAP V13

This is an excerpt from Manning's book Modern Fortran: Building efficient parallel applications MEAP V13.

For now, we can work with only the main program. We’ll dive deep into functions and subroutines in chapter 3, and modules in chapter 4.

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
fortran procedures overview

Subroutine--A subroutine is another kind of procedure. In many respects, it’s similar to a function, with two notable differences:

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
fortran contains subroutine

3.3.1 Defining and calling a subroutine

Let’s see the difference between a subroutine and a function in an example. The following listing defines a subroutine add that’s equivalent to our function sum from the previous subsection.

Listing 3.13. Definition of a subroutine that calculates the sum of integers a and b and stores the result in an integer res
language="fortran" linenumbering="unnumbered">subroutine add(a, b, res)
  integer, intent(in) :: a, b #1
  integer, intent(out) :: res #2
  res = a + b
end subroutine add
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage