[J3] Default values for optional arguments

William Clodius w.clodius at icloud.com
Wed Jan 20 17:55:51 UTC 2021


A few points:

	1. Having a default value means that the argument ia always present with a value so the present(argument) test is never appropriate. The easiest way to express this in standardess I believe is to forbid an argument from having both the optional and default attribute at the same time and requiring that actual arguments to the present function must have the optional attribute.
	2. There are at least there possible syntaxes for declaring that a dummy argument has a default value: 
providing the value after the declaration
   subroutine foo(a)
     integer, intent(in), default :: a = 42
providing the value in the default attribute
   subroutine foo(a)
     integer, intent(in), default(42) :: a
providing the value in the dummy argument list
   subroutine foo(a=42)
     integer, intent(in), default :: a
    3. The use of default arguments provides a small optimization of the code in that the test and branch at runtime that is needed to assign a default replacement for an optional argument, can be resolved by the processor at compile time as the call site for the procedure.



> On Jan 20, 2021, at 12: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.  One idiom
> to do this would be
> 
>  subroutine foo(a, b)
>    integer, intent(in), optional :: b
>    integer :: b_val
> ...
>    if (present(b)) then
>      b_val = b
>    else
>      b_val = 42
>    end if
> 
> and then use b_val and c_val. This idiom is wasteful of lines (as
> written, it takes five lines of code for a single default value). More
> importantly, it is also error-prone because it is necessary to remember
> to use b_val instead of b.
> 
> The first drawback could be mitigated by doing something like
> 
>  if (present(b)) b_val = b
>  if (.not.present(b)) b_val = 42
> 
> (not very clear, in my opinion) or by using yet-to-be-added conditional
> expressions, but people would still have to use a different variable
> name for essentially the same thing.
> 
> 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?
> 
> Best regards
> 
>    Thomas

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.j3-fortran.org/pipermail/j3/attachments/20210120/36575b71/attachment-0001.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 1619 bytes
Desc: not available
URL: <https://mailman.j3-fortran.org/pipermail/j3/attachments/20210120/36575b71/attachment-0001.bin>


More information about the J3 mailing list