Search code examples
fortranfortran90optional-arguments

Is the "present()" intrinsic evaluated at compile time


When dealing with optional arguments in fortran I believe it's typical to branch using the present() intrinsic, i.e.:

subroutine foo(ii,jj)
    implicit none
    integer, intent(in) :: ii
    integer, optional   :: jj

    if (present(jj)) then
! do something
    else
! do something else
    end if

end subroutine foo

My assumption (coming from a C++ world) is that present() is hopefully a compile-time construct, and that there won't be any associated runtime performance penalty. I expect that the compiler should be able to (should be required to?) optimise the if statement shown above away, depending on whether foo(ii) or foo(ii,jj) is called.

How is the present() intrinsic handled by compilers in practice? Does the fortran spec guarantee certain behaviour?


Solution

  • PRESENT is a runtime concept - to the extent that the presence of an argument may depend on aspects of the program that cannot be determined until runtime (based on input read from a file or similar).

    The implementation of the equivalent of PRESENT in a C++ program would similarly be a runtime concept. Note that C++'s defaulted arguments feature is not quite the same concept as Fortran's optional arguments feature (though it could be part of an equivalent implementation).

    Beyond compiler optimization cleverness, if you want compile time resolution of things similar to C++'s defaulted arguments or function overloading, then consider using multiple specific procedures behind a generic name, one variant of the specific with the "optional" argument, the other without.