Skip to content

Allow setting default value for optional dummy argument #22

Open
@milancurcic

Description

@milancurcic

Problem

Currently, Fortran doesn't allow setting a default value for optional dummy arguments. If declaring a dummy argument as optional, the user must:

  1. Manually make appropriate checks about whether the actual argument is provided by the caller;
  2. Use a separate variable inside the procedure because the code must not reference the optional dummy argument if not present.

Example

Example of a quadratic function that optionally allows evaluation of its linear form:

real function quadratic(x, a, b, c)  
  ! returns a + b * x + c * x**2 if c is present and a + b * x otherwise
  real, intent(in) :: x, a, b
  real, intent(in), optional :: c
  real :: c_tmp ! use separate variable to avoid referencing non-present arg
  if (present(c)) then
    c_tmp = c
  else
    c_tmp = 0 ! default value if c is not present
  end if
  quadratic = a + b * x + c_tmp * x**2
end function quadratic

Checking for presence of the optional argument and using a temporary variable is cumbersome and error-prone, and it is even more so if the same needs to be done for many optional arguments.

Solution

Allow setting the default value of the optional argument in the function (or subroutine) statement by using the assignment operator =:

real function quadratic(x, a, b, c=0)
  ! returns a + b * x + c * x**2 if c is present and a + b * x otherwise
  real, intent(in) :: x, a, b
  real, intent(in), optional :: c
  quadratic = a + b * x + c * x**2
end function quadratic

This is similar to how Python keyword arguments are defined.

Comments

  • The proposed syntax is complementary to the existing syntax, that is, it doesn't break existing code;
  • Its style is more or less Fortranic and consistent with other syntax elements;
  • Same syntax as Python keyword args, so it would be intuitive to Python developers learning Fortran;
  • Could be implemented completely as a pre-processor, for a proof-of-concept.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Clause 8Standard Clause 8: Attribute declarations and specificationsFortran 202yProposals targeting the standard after F2023under considerationHas been submitted to the committee

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions