Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

fortran90 - What is the purpose of result variables in Fortran?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...