Can an OPTIONAL, VALUE argument be set if not PRESENT?

The eig function here sets an optional, value argument that is not present, and the code

module m
implicit none
subroutine sub(i)
integer, value, optional :: i
if (.not. present(i)) i = 0
print "(a,i0)", "i = ",i
end subroutine sub
end module m

program main
use m, only: sub
implicit none
call sub(5) ! i = 5
call sub()  ! i = 0
end program main

compiles and runs with gfortran, with output shown in the comments. So it is allowed to set an optional , value argument that is not present?

In procedures with optional arguments not having the value attribute, I need set a local variable that shadows the optional argument and remember not to use the optional argument without testing that it is present. Optional value arguments appear convenient.

1 Like

It seems it is not standard-conforming. The 2023 Draft says: Argument association
A present dummy argument with the VALUE attribute becomes argument associated with a definable anonymous data object whose initial value is the value of the actual argument. Argument presence and restrictions on arguments not present
An optional dummy argument that is not present is subject to the following restrictions.
(1) If it is a data object, it shall not be referenced or be defined. If it is of a type that has default
initialization, the initialization has no effect.

Edit: but I must admit that the idea is not that bad, for an optional dummy which is of intent(in) as it would save the hassle with extra variable. So maybe the future Standard could allow assigning to an optional, value dummy arg which is not present.


It fails on execution with ifx

1 Like

As it should.


I will note that as a user I would like the compiler to give me a nice error message either at compile time or at runtime (in Debug mode) explaining what the problem is. No segfaults or undefined behavior in Debug mode.


Well, it could be worse - the program could silently deliver undefined behavior. I note that NAG allows this to run and prints zero for the second call.

Malcolm pointed out that if you enable the checking option, nagfor gives you:

$ a
i = 5
Runtime Error: m.f90, line 6: Reference to OPTIONAL argument I which is not PRESENT
Program terminated by fatal error

Yes, the NAG compiler is solid, you have to really try to cause a segfault or undefined behavior when all the Debug checking options are on.