Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29111 Discussions

Efficient Use of Optional Arguments in a Function

lrego-developer
New Contributor I
336 Views

Hello,

I need to call a function (defined below) multiple times in my program. Depending on the context, arguments B and C may or may not be defined. Sometimes both will be provided, sometimes only one, and sometimes neither.

I’m looking for an efficient way to handle this without creating an interface to cover all possible combinations, as that would make things too messy.

Here’s the function:

function func(A, B, C) result(res)
type(some_type), intent(in) :: A
type(some_type), optional, intent(in) :: B
type(some_type), optional, intent(in) :: C
end function func

Does anyone have suggestions for implementing this in a clean and efficient way?

Thank you!

0 Kudos
1 Solution
Steve_Lionel
Honored Contributor III
322 Views

The way I usually handle this is to have local variables for each optional argument, and do something like this:

function func(A,B,C) result(res)
type(some_type), intent(in) :: A
type(some_type), optional, intent(in) :: B
type(some_type), optional, intent(in) :: C
!
type(some_type) :: lcl_B, lcl_C
if (present(B)) then
  lcl_B = B
else
  lcl_b = 0 ! Whatever a default value would be
end if
...

and then reference the "lcl_" variables in the rest of the routine.  (The F2023 conditional expression feature will make this easier when available.) 

If instead you want entirely different functionality depending on the combination of present arguments, you may want to rethink that and use generic interfaces without optional arguments.  

View solution in original post

0 Kudos
1 Reply
Steve_Lionel
Honored Contributor III
323 Views

The way I usually handle this is to have local variables for each optional argument, and do something like this:

function func(A,B,C) result(res)
type(some_type), intent(in) :: A
type(some_type), optional, intent(in) :: B
type(some_type), optional, intent(in) :: C
!
type(some_type) :: lcl_B, lcl_C
if (present(B)) then
  lcl_B = B
else
  lcl_b = 0 ! Whatever a default value would be
end if
...

and then reference the "lcl_" variables in the rest of the routine.  (The F2023 conditional expression feature will make this easier when available.) 

If instead you want entirely different functionality depending on the combination of present arguments, you may want to rethink that and use generic interfaces without optional arguments.  

0 Kudos
Reply