Segmentation fault with optional arguments in Fort

2020-03-20 05:36发布

问题:

I can use Fortran optional argumenrs with subroutines with intent(in) and intent(inout), but with functions optional arguments work only with intent(in), right? With intent(inout) I get segmentation faults in the following code:

real function foo(x, tol) 
    real, intent(in) :: x
    real, optional, intent(inout) :: tol
    if( .not. present(tol) ) tol = 1e-6
    !...
end function foo

回答1:

I found the problem, I used the variable even when not present on the fourth line (in tol = 1e-6):

real function foo(x, tol) 
    real, intent(in) :: x
    real, optional, intent(inout) :: tol
    if( .not. present(tol) ) tol = 1e-6
    !...
end function foo 

But I would like to use it even when not present and set a default value, like when in C++ we do something like that

double foo(double x, double tol=1e-6)

Unfortunately, it seems it is not possible in Fortran.