Open
Description
Problem
Currently, Fortran doesn't allow setting a default value for optional dummy arguments. If declaring a dummy argument as optional
, the user must:
- Manually make appropriate checks about whether the actual argument is provided by the caller;
- 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.