Showing results for 
Search instead for 
Did you mean: 
New Contributor III

passing a missing optional argument to another subroutine that takes non-optional argument

Is this a valid standard-conforming Fortran code:

module NonOptionalArg_mod
    subroutine nonOptionalArg_func(optionalArg)
        integer, intent(in) :: optionalArg
        !write(*,*) "optionalArg: ", optionalArg
    end subroutine nonOptionalArg_func
end module NonOptionalArg_mod

module OptionalArg_mod
    use NonOptionalArg_mod
    subroutine optionalArg_func(optionalArg)
        integer, intent(in), optional :: optionalArg
        call nonOptionalArg_func(optionalArg)
    end subroutine optionalArg_func
end module OptionalArg_mod

program optionalProg
    use OptionalArgFirst_mod
    implicit none
    call optionalArg_func()
end program optionalProg

The main program calls a subroutine that takes an optional argument. The function then passes the non-existing optional argument to another function that takes a non-optional argument. The code compiles fine with ifort 19.4 and as long the optional argument is not used, it does not lead to any runtime errors.

0 Kudos
2 Replies
Black Belt

By passing an optional argument as an actual argument to a subprogram, which in turn expects that argument to be always present, you deprive yourself of the ability to check in that subprogram whether the argument is present and only use it if it is present.

Another way of viewing the situation is to regard an optional argument as being represented by a null-pointer. You can pass that null-pointer around, as long as it never gets dereferenced or checked for nullity. This is somewhat analogous to having an argument that is allocatable in the caller but has not been declared as allocatable in the callee.

In your program, on Line-19, "use OptionalArgFirst_mod" should have been "use OptionalArg_mod"

0 Kudos
Black Belt Retired Employee

The standard says "a nonoptional dummy argument shall be present". In your example, it isn't, so your program is non-conforming. The standard does not require detection of this behavior and you should not rely on what happens now.

0 Kudos