What is the purpose of result variables in Fortran?

Introduced at the same time as the result was recursion. Before we get to how a recursive function comes about, some clarification on what a result variable is.

The function result is always returned through a result variable, whether result is used or not.1 With result the result variable has the name specified, and without it the result variable has the same name as the function. In this latter case use of the name is a reference to the result variable and not the function.

So, if the function foo has result variable foo then we can’t do direct recursion:

recursive function foo(n)
  foo = foo(n-1) ! Oh dear
end function

result comes about so that we can have

recursive function foo(n) result(res)
  res = foo(n-1) ! Yay
end function

[1] Well, this is true up until Fortran 2008, when the definition of variable changed. For modern Fortran use instead the term function result.

Leave a Comment