Advantages of Fortran functions over subroutines

Early fortran, before f66, had the requirement that all function names ended in the letter F.

As others have mentioned, allocation of memory for array-valued and derived-type valued functions, or arguments in the subroutine case, is sometimes very expensive relative to the rest of the effort within the subprogram. That kind of programming convention should be avoided when performance is critical. This is one of the problems with, for example, the matmul() intrinsic function interface – the programmer has no direct control over where and when the storage for the result is allocated, how often it is allocated, and if the same intermediate storage can be reused for multiple matmul() references.

Another problem that arises with functions is when the function result is used in a write statement. Adding an innocent looking debug write statement somewhere down the call chain of function references suddenly causes your program to behave oddly, or to hang, because of the restriction in fortran against recursive i/o.

I remember this thread from last year, Execute_command_line problem. It also involved a function reference in a write statement, seemingly related to recursive i/o but not in an obvious way.

1 Like