Determine variable names dynamically according to a string in Fortran

后端 未结 4 1617
春和景丽
春和景丽 2020-12-02 02:26

I want to create a dynamic variable name using Fortran.

The variable name will be obtained by concatenating a string and another string/integer. Then I want to us

4条回答
  •  离开以前
    2020-12-02 03:17

    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.

提交回复
热议问题