Search code examples
fortrangfortranfortran90intel-fortran

There any way to get name of Fortran variable?


I like how it's implemented in Python. Example(Python):

x = 1
y = 2
print(f"{x = }, {y = }")
# x = 1, y = 2

Im want to handle the errors and then print the variable name. Example(Fortran):

function check(var)
...
    if (var < 0) print *, 'Error: var < 0'
...
end function check

Solution

  • There is no way in Fortran to get a variable name dynamically as variable names and types are required at compile time.

    You could used Fortran derived types to associate a label to a value:

    program derived_types
    ! Define
    type :: labelled_int_var
      character(len=15) :: label
      integer :: value
    end type
    
    ! Declare
    type(labelled_int_var) :: x,y
    
    ! Initialize
    x%value = 1
    x%label = 'x'
    
    y%value = 2
    y%label = 'y'
    
    ! Use
    write(*,*) trim(x%label), " =", x%value, ", ", trim(y%label), " =", y%value
    
    end program