Search code examples
fortran

Can you reuse the function result in Fortran?


I have read that depending on the value of a function-result variable is nonstandard Fortran.

integer function my_sum(x, n)
  integer, dimension(n), intent(in) :: x
  integer              , intent(in) :: n

  integer :: i

  my_sum = 0
  do i = 1, n
    my_sum = my_sum + x(i) ! Error! Cannot re-use my_sum
  end do
end function

Instead we must use a local variable and assign it at the end of the function. To be clear, I'm not expecting the value to be saved between calls, but within the function body as if it were a local variable.

Is this statement true in Fortran 90 or later? It works on my compiler (Intel) but I'm not sure if this is standard and haven't found anything besides random university slides online.

Edit: I found the source for the function name thing. It's in Slide 4 of this presentation linked to from the official fortran-lang.org site.

Somewhere in a function there has to be one or more assignment statements like this:

function-name = expression

where the result of expression is saved to the name of the function.

Note that function-name cannot appear in the right-hand side of any expression.


Solution

  • I don't think that what you read is true ...

    For the function result variable, which unless your program has made other provisions, has the same name as the function itself, the latest version of the language standard that I have to hand (BS ISO/IEC 1539-1:2018 15.6.2.2 Note 1) states:

    The function result is similar to any other entity (variable or procedure pointer) local to a function subprogram. Its existence begins when execution of the function is initiated and ends when execution of the function is terminated. However, because the final value of this entity is used subsequently in the evaluation of the expression that invoked the function, an implementation might defer releasing the storage occupied by that entity until after its value has been used in expression evaluation.

    I interpret that to mean that your compiler is correct to compile the code. I've also used the result variable in ways such as your codes shows and cannot recall ever encountering a problem with such usage.