On 2013-02-21 7:03 AM,
john.chl...@gmail.com wrote:
> Which is better practice:
>
> function MxV(A, X) result(ans) ! ans = AX
> real(kind=DP), dimension(:,:), intent(in) :: A
> real(kind=DP), dimension(:), intent(in) :: X
> real(kind=DP), dimension( size(A,1) ) :: ans
>
> or
>
> subroutine MxV( Y, A, X ) ! Y = AX
> real(kind=DP), dimension(:), intent(out) :: Y
> real(kind=DP), dimension(:,:), intent(in) :: A
> real(kind=DP), dimension(:), intent(in) :: X
>
> ?
>
> The first can be used in RHS expressions and makes for more readable
> code.
If you are just going to use the functions as the entirety of an
expression on the right hand side of an assignment, then that's a bit
ho-hum. If you are going to use them in more complicated expressions,
then I think the argument for a function builds strongly.
The second will use the reference to Y to write the answer
> into. I assume the return value for functions is placed on the call
> stack. I know from C++ coding experience when declaring local
> variables, which go on the call stack, this can easily blow up in
> your face.
Function results *may* go on the stack. They may not too. They *may*
require additional copying of the result in the expression that uses the
function. They may not too. I think these aspects are secondary to
readability and robustness, but perhaps my expectations of my compilers
are too high.
Personally, structure constructor "overloads" aside, if I can't make the
procedure pure, I don't use a function. If I can make a pure function,
then I think about it some more and/or reach for my lucky coin.