The name of a subroutine can be a variable in Fortran? [duplicate]

瘦欲@ 提交于 2020-04-06 01:54:45

问题


I was wondering if there is something similar to this in Fortran. Of course this example does not compile but I think you can get the idea.

program test
    character(1):: sub

    sub='A'
    call sub

    sub='B'
    call sub
end program

subroutine A
    print*,'OK! A'
end subroutine A

subroutine B
    print*,'OK! B'
end subroutine B

回答1:


You cannot accomplish this by setting a character variable, but you can do this with procedure pointers. I've modified your example slightly to implement that. See:

program test
 implicit none

 abstract interface
    subroutine no_args
    end subroutine
 end interface

 procedure(no_args), pointer :: sub => null()

 sub => A
 call sub

 sub => B
 call sub

contains

subroutine A
 implicit none
 print *,"OK! A"
end subroutine

subroutine B
 implicit none
 print *,"OK! B"
end subroutine

end program

The changes are:

  • Define an interface for the procedure pointer
  • Declare sub as a procedure pointer to that abstract interface

You can then assign sub to subroutines that take no arguments (since that is the what the interface says) and call them through sub the way you envision.




回答2:


Closest you could get is function/procedure pointers, but that would be fortran-2003. BAsically, given input 'A' or 'B' you set pointer to point to either subroutine A or subroutine B. More details at How to alias a function name in Fortran



来源:https://stackoverflow.com/questions/30308601/the-name-of-a-subroutine-can-be-a-variable-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!