[J3] Default values for optional arguments

Bill Long longb at cray.com
Wed Jan 20 12:28:31 UTC 2021



> On Jan 20, 2021, at 2:21 AM, Steven G. Kargl via J3 <j3 at mailman.j3-fortran.org> wrote:
> 
> On Wed, Jan 20, 2021 at 08:32:18AM +0100, Thomas König via J3 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
> 
> Looks straightforeward and easy for a reader to comprehend.
> 
> 
>> 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
>> 
> 
> Doesn't this imply the SAVE attribute?  Although, I believe 
> th Standard says SAVE and OPTIONAL conflict.
> 

There was a proposal for default optional argument values for F202X that failed for the reason given above.   Something like

integer, intent(in), optional, default(42) :: b

might work.If this were to work, then subsequent tests for Present(b) would have to return true to avoid conflicts with existing code. There might be other side effects that are undesirable. 
But given that the existing workarounds are quite simple, and already widely used, it’s not clear this is a good expenditure of committee time. 


Cheers,
Bill


>> or
>> 
>>  integer, intent(in), optional, default (42) :: b
>> 
>> Opinions?
>> 
> 
> What's wrong with
> 
>   b_val = 42
>   if (present(b)) b_val = b
> 
> ?
> 
> If you want to do it on one line
> 
>   b_val = 42 ; if (present(b)) b_val = b
> 
> -- 
> Steve

Bill Long                                                                       longb at hpe.com
Engineer/Master , Fortran Technical Support &   voice:  651-605-9024
Bioinformatics Software Development                      fax:  651-605-9143
Hewlett Packard Enterprise/ 2131 Lindau Lane/  Suite 1000/  Bloomington, MN  55425






More information about the J3 mailing list