0

I have a function in a Fortran module with two required arguments and one optional argument. If the optional argument is not present, I would like to set a default value for it within the function.

When I use the function, I get a segmentation fault: Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

The backtrace refers to the first line of

if (.not. present(optionalArg)) then
    optionalArg = 2
end if

and the function is defined

function func(reqArg1, reqArg2, optionalArg)
    real(kind=real64), intent(in) :: reqArg1
    integer, intent(in) :: reqArg2
    integer, optional :: optionalArg
    real(kind=real64), dimension(reqArg2) :: func
    ...

Is this the correct way to define a function with an optional argument? I've tried writing an explicit interface for the function both in the module where the other function is called and in the module where the function is defined, but both give me errors. If I put the interface in the module where the function is called I get Error: Cannot change attributes of USE-associated symbol func since the module is already included with a USE statement, and if I put the interface in the function's module I get an error about the function already having been defined when the compiler reaches the actual function definition within the CONTAINS block.

zaen
  • 326
  • 3
  • 14

1 Answers1

1

This code is clearly invalid

if (.not. present(optionalArg)) then
    optionalArg = 2
end if

You cannot access the value of an optional argument that is not present. You cannot read it and you cannot set it, you have to use a different local variables, I am sure there are examples in other questions and answers here.

if (.not. present(optionalArg)) then
    optionalArg_local = 2
end if
  • Thanks, I was working up an example but this seems to be the answer. I formatted the setting of a local variable as was shown in lines 14-15 on the first example program on [this thread in the Intel forums](https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/537619) and the error is gone now. – zaen Apr 26 '19 at 20:35