Expose saved/static target variable to scope outside

Viewed 75

Is the following code where a local, saved variable is exposed to an outside scope valid Fortran(>=2003) code?

I intentionally did not specify a year for the standard. If the answers differ for different standards, assuming that pointers are supported, I would be also happy to hear the answer.

program test_save
    implicit none

    integer, pointer :: ptr

    ptr => get_number(5)

    write(*, *) ptr

contains

    function get_number(n) result(res)
        integer, intent(in) :: n
        integer, pointer :: res
        integer, target, save :: internal_n
        internal_n = n
        res => internal_n
    end function
end program
1 Answers

The point to consider is whether the target of res remains defined when the function exits (F2018 19.6.6p1(16)). Because the target has the SAVE attribute, it does remain defined (F2018 19.6.6p1(3)), and therefore the pointer remains defined.

Related