[J3] Default values for optional arguments

Vipul Parekh parekhvs at gmail.com
Fri Jan 22 03:36:34 UTC 2021


On Wed, Jan 20, 2021 at 2:32 AM Thomas König via J3 <
j3 at mailman.j3-fortran.org> wrote:

>
> A somewhat common thing to do for optional arguments is to set them
> to a default value if the caller did not specify anything.  ..
>


> What could help is to add some way to express default initialization for
> optional arguments, something along the lines of
>
>    integer, intent(in), optional :: b = 42
>
> or
>
>    integer, intent(in), optional, default (42) :: b
>
> Opinions? ..
>


I agree with Malcolm in terms of the risk of "syntactic cyanide" with
pursuing any of this now considering all the work that has gone into the
language since Fortran 90.  And given the introduction of PRESENT starting
Fortran 90, there is also the risk of a semantic landmine with doing any of
this now.

For the simple example given in the original email, an alternative "idiom"
supported by the current standard is the following:
--- begin example ---
module foo_m
   generic :: foo => foo_1, foo_2
contains
   subroutine foo_1( a, b )
      integer :: a
      integer(..), intent(..) :: b ! <-- not optional
      ..
      ! subprogram including instructions that reference 'b'
   end subroutine
   subroutine foo_2( a )
      integer :: a
      call foo_1(a, b=42 )
   end subroutine
end module
--- end example ---

Compared to the "cost" of all work in the standard to introduce "default
values" of optional arguments, the above is a relatively inexpensive
workaround that is reasonably safe and efficient while maintaining
readability  Note there is no code vulnerability here with 'b' versus
'b_val'.

Regards,
Vipul Parekh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.j3-fortran.org/pipermail/j3/attachments/20210121/1c89982c/attachment-0001.htm>


More information about the J3 mailing list