Determine variable names dynamically according to a string in Fortran

I fear that you will not be able to do this. Fortran requires that variables have names and types at compile time. You (or other SOers) may come up with some kludge to simulate what you want, but it will be a kludge.

Why do you want to do this in Fortran ? There are plenty of languages around which do permit this sort of variable declaration.

EDIT

Well, I thought about it some more, and here’s a kludge, unfinished. First a UDT for ‘dynamic’ variables:

type dynamic_var
  character(len=:), allocatable :: label
  class(*), allocatable :: value
end type

declare some space for such variables:

type(dynamic_var), dimension(:), allocatable :: run_time_vars

and, working with your original data

allocate(run_time_vars(10)) ! No error checking, reallocate if necessary
! lots of code
write(run_time_vars(1)%label,'(a1,i1)') my_string, my_integer
allocate(run_time_vars(1)%value, source = my_value)

This compiles, but doesn’t run and I’m not going to stay long enough to fix it, I’ll leave that as an exercise to anyone who cares.

  • The write to the label field isn’t right.
  • The sourced allocation to the value field doesn’t seem to work correctly. Might need to write a ‘decode’ function to use like this:

allocate(run_time_vars(1)%value, source = decode(my_value))

Like I said, it’s a kludge.

Leave a Comment

tech