In Fortran, there are two standard ways to return a result from a function. The first one is by assigning the return value of the function to the function name.
function foo()
integer :: foo
foo = 10
end function foo
The second form, standardized in Fortran 90 is through a "result" variable.
function foo result(res)
integer :: res
res = 10
end function foo
Calling either form of the function returns the value 10. My question is, what was the rationale of the Fortran 90 committee for introducing result variables? Were they standardizing a common practice? Or were they allowing programs to be more modular by not tying the function name to a function result. For example, in the second version of foo()
, the name of the function foo()
could be changed to bar()
and the function would still work as expected when called.
However, I may be wrong. Does anyone know what the actual rationale was for introducing result variables?
This is because the function itself returns the value, and Fortran needs to know what sort of value it is. Secondly, within the functions, it is the name of the function which is used to return the final value to the main program.
A Fortran variable can be considered as a box that is capable of holding a single value of certain type. Thus, a variable has a name, the variable name and a type. The way of choosing a name for a variable must fulfill the rules of composing a Fortran identifier.
Fortran has five intrinsic data types: INTEGER , REAL , COMPLEX , LOGICAL and CHARACTER . Each of those types can be additionally characterized by a kind.
A Fortran function is similar to a mathematical function, which takes one or many parameters as inputs and returns a single output value. A Fortran subroutine is a block of code that performs some operation on the input variables, and as a result of calling the subroutine, the input variables are modified.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With