3

I am confused between various syntax for functions in fortran.

 function func(i) result(j)
...
end function fun

Here is second example

 real function func (x)
...
end function func

This is third example

  real function func (x)
    ...
    return
    end function func

Which one is appropriate syntax as per modern fortran standard? And in the 2nd and 3rd example, if I declare multiple variables in the program of type real, how does compiler know which variable to return?

IanH
  • 21,026
  • 2
  • 37
  • 59

1 Answers1

4

All of your examples are appropriate, depending on circumstances. Aspects of this come down to style preferences.

If the opening function statement does not have a RESULT specifier, inside the body of the function the function result has the same name as the function.

You can use the RESULT specifier in the opening function statement, as in your first example, to change the name of the function result to something else.

You might want to do this because you prefer to use a name for the function result other than the function name. You might need to do this if you actually want to recursively invoke the function.

You can either specify the type of the function in the opening statement (as per your second or third examples), or you can specify the type of the function in the specification part (in the body) of the function itself (which is what is presumably happening in your first example, implicit typing aside). Attributes of the function result must be specified in the body, so as a matter of style some people prefer to keep everything together in the function body (this also avoids some obscure complications associated with scope and the ordering of definitions). You should not be using implicit typing, ever.

Your last example simply has an explicit return statement at the end of the executable part of the function. This is superfluous - the function automatically returns when execution reaches the end of the executable part of the function. Some people prefer the explicit return, perhaps because they have a deep seated fear that the compiler might suddenly forget to automatically return, others think that this is absurd foolishness.

Repeating - the name of the function result is the function name, if there is no RESULT clause in the opening function statement, otherwise it is the name in the result clause.

IanH
  • 21,026
  • 2
  • 37
  • 59