Search code examples
fortranstandards-compliance

Aliasing in Fortran function


For optimisation reasons, Fortran enforces that the dummy arguments of a subroutine or function are not alias, i.e., they do not point the the same memory place.

I am wondering if the same constraint applies to the returned value of a function. In other words, for a given myfunc function:

function myfunc(a)
    real, intent(in) :: a(:)
    real             :: myfunc(size(a))
    myfunc = a * 2
end function myfunc

is it standard-compliant to write: a = myfunc(a) and b = myfunc(a) ?


Solution

  • The arguments of a function and function return value are different things. Contrary the previous answer, the functional arguments ARE passed by reference, or by copy-in copy-out, unless they are declared as dummy arguments with the VALUE attribute. This is a major difference of Fortran vs. C.

    However, if the function value is constructed by normal assignment (=) and not by pointer assignment (=>) they are separate entities. In your code, the value of myfunc is got by copying the value of a. Therefore no standard rules are broken by a = myfunc(a) or b = myfunc(a).