5

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
3
  • 2
    inout should work see here stackoverflow.com/questions/3121954/… Commented Aug 26, 2013 at 21:35
  • 1
    Maybe the segfault comes from not testing for presence of the argument? Commented Aug 27, 2013 at 6:21
  • 1
    Maybe you should post a minimal (not) working example... Commented Aug 27, 2013 at 9:02

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You can't define/assign/use an optional argument that is not present. You have to use another variable. For example, name you optional var opt_tol, and define tol in your program (if present(opt_tol) then tol=opt_tol else tol=default value). See section 12.4.1.6 of the Fortran 2003 standard.
A frequent mistake of those just learning about OPTIONAL is not realizing that the caller of a procedure with OPTIONAL requires an explicit interface to the called routine. See software.intel.com/en-us/forums/topic/275071#comment-1548437 and software.intel.com/en-us/blogs/2012/01/05/… for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.