Usage of Fortran statement functions

2019-01-28 16:50发布

问题:

I read about statement functions, such as the example:

C(F) = 5.0*(F - 32.0)/9.0

Isn't this the same as:

C = 5.0*(F - 32.0)/9.0

i.e. without the function part, or maybe I'm missing something?

If they're not the same, when do I need to use a statement function?

回答1:

C = 5.0*(F - 32.0)/9.0

is just assignment to a variable C, it can be anywhere and is evaluated once every time when the program flow reaches it.

C(F) = 5.0*(F - 32.0)/9.0

is a statement function, and can be evaluated any time it is in the scope by, e.g., C(100) which returns approximately 37.8.

From some code

  xx(i) = dx*i

  f(a) = a*a

  do i = 1, nx
     x = xx(i)
     print *, f(x)
  end do

The f(x) in the print statement is evaluated with each new value of x and yields a new value. The value of x is also result of evaluation of the statement function xx on the previous line.

But statement functions are now (in Fortran 95) declared obsolete. Better use internal functions in any new code. E.g.,

program p
  implicit none
  !declarations of variables x, i, nx, dx

  do i = 1, nx
     x = xx(i)
     print *, f(x)
  end do
contains

  real function xx(i)
    integer, intent(in) :: i
    xx = dx*i
  end function

  real function f(a)
    real, intent(in) :: a
    f = a*a
  end function
end program