Probably neither, though as usual with these things, the answer depends on specific circumstances.
Assuming a non-elemental operation, I would tend to write such a function (in a module) as:
function times2(x) result(y)
real, intent(in) :: x(:)
real :: y(size(x))
y = 2*x
end function
The above has an assumed shape dummy argument, with automatic function result. It:
is available when writing to the Fortran 95 standard;
specifies explicitly in source the dependence of the size of the function result on the function arguments, which may (or may not) help readers of your code understand what is going on (one such reader is the compiler itself, which might help it with optimisation);
may (or may not) avoid intermediate copies of the value of the array;
may (or may not) require space for the function result or equivalent temporary on the stack.
If the operation was elemental (i.e. the same operation on each element, as per the actual example given), I would write an elemental function. The source for such a function takes a scalar argument and provides a non-allocatable, non-pointer scalar result.
elemental function times2(x) result(y)
real, intent(in) :: x
real :: y
y = 2*x
end function
I typically use deferred shape allocatable function results when the shape (or some other attribute) of the function result is not able to be described by a simple specification expression. Allocatable function results:
requires writing to at least the Fortran 2003 standard;
may require an extra heap memory allocation/deallocation pair above what is strictly necessary, which may (or may not) have performance implications;
may not require the same use of the stack as the automatic result case, which may (or may not) avoid stack overflow problems at execution time.
Compiler implementation details (including compiler options) affect the comparison. In particular, differences in how a compiler manages the memory for temporaries may make the two approaches converge in terms of their requirements for stack and heap allocations.
Avoid explicit shape array dummy arguments, unless you have particular requirements.
sqrt
is a function, that means you can evaluate expresions likesqrt(1/(1 + sqrt(x))
. Imagine thatsqrt
was a subroutine... – Awakencross(u,v,n)
? (sorry if I missunderstood you @roygvib) – Awakeny(size(x))
withx(:)
still (which I admit is what I thought you'd done: I probably skipped over the actual code based on the most minimal difference between automatic and deferred.) – Bain