- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.

- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page