johncg
johncg

Reputation: 35

How to execute a subroutine whose name is just known in runtime, in Fortran 90?

Suppose I have a program in Fortran with various subroutines, I don't know a priori all the subroutines, and an user supplies the name of one of them via command-line, just as follows:

    program subroutine_name

Therefore, I store the subroutine_name in a character variable. In this way, I can't declare a external variable to store the subroutine. So, how can I call it just knowing its name? Is it possible by this way, or is there another way to accomplish this?

Upvotes: 1

Views: 385

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

There isn't really a way to write a Fortran statement such as

call character_variable_containing_subroutine_name

It goes against the grain of statically-typed compiled languages such as Fortran to provide that sort of facility.

Of course, if you had asked can I provide an input argument to a Fortran program which will, at run-time, determine the execution path the program takes then the answer is of course. I'll ignore any complications of your situation and suppose that you want to call one of sin, cos or tan.

First, capture the text of the argument to the program into a character variable:

character(len=*) :: user_choice
...
call get_command_argument(1,user_choice)
...
select case (user_choice)
case ('sin')
   ... do stuff with sin
case ('cos')
   ... do stuff with cos
case ('tan')
   ... do stuff with tan
case default
   ... do whatever
end select

You could make this more elaborate by using procedure pointers. For example, you might define:

pointer :: rp
interface
 real function rp(inval)
    real, intent(in) :: inval
  end function rp
end interface

and then replace the first version of the select case construct by something like:

select case (user_choice)
case ('sin')
   rp => sin
case ('cos')
   rp => cos
case ('tan')
   rp => tan
case default
   ... do whatever
end select

This might simplify later code. I guess it might also make it more complicated.

Note that I haven't tested any of these fragments, my syntax might be a little wonky.

Upvotes: 3

Related Questions