[J3] Default values for optional arguments
Shterenlikht, Anton
anton.shterenlikht at hpe.com
Wed Jan 20 08:06:24 UTC 2021
I see no problem here, that needs to be solved.
Perhaps this style is marginally more consise and clear:
subroutine foo(a, b_optional)
integer, intent(in), optional :: b_optional
integer :: b = 42
...
if (present(b_optional)) b = b_optional
On the other hand, being verbose and explicit
with optional arguments is probably a good thing,
as this is a frequent source of user errors.
So your original form might be preferred.
Anton
> On 20 Jan 2021, at 07:32, 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
More information about the J3
mailing list