0

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
francescalus
  • 30,576
  • 16
  • 61
  • 96
gonza85
  • 3
  • 2
  • If it doesn't compile then it seems it mustn't work. Aren't you answering your own question? – KevinDTimm May 18 '15 at 16:41
  • Are you asking "**Can** the name of a subroutine be a variable in FORTRAN?" If not, please provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). Please read "[ask]" for additional tips on how to ask a question. – Deacon May 18 '15 at 16:46
  • You can't do calling based on subroutine names, but you can use procedure pointers instead: see http://stackoverflow.com/questions/8612466/how-to-alias-a-function-name-in-fortran/8612679. How useful that question is really depends on exactly what you want to do. – francescalus May 18 '15 at 16:46

2 Answers2

3

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.

casey
  • 6,855
  • 1
  • 24
  • 37
0

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

Community
  • 1
  • 1
Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64