3

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
2
  • 2
    Can't see anything wrong with this in Fortran90 and onwards, but I'm not the person to quote chapter and verse of the standard at you. Commented Sep 5, 2021 at 17:35
  • 2
    This can be quite hard to answer in the positive (so much of the Fortran standard is about restrictions and you won't find many parts which says "a Fortran program is allowed to ..."). What standard of proof are you hoping to find? Commented Sep 5, 2021 at 17:52

1 Answer 1

4

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.

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

Comments

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.