Wexel
Wexel

Reputation: 45

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

Upvotes: 1

Views: 622

Answers (2)

Serge3leo
Serge3leo

Reputation: 549

For Intel and GNU fortran compilers (by question tags), as well as for many other compilers, you can use a preprocessor (-cpp flag).

#if defined(__GFORTRAN__) || defined(NAGFOR)
#   define CPPSTR(a) "a"
#else
#   define CPPSTR(a) #a
#endif

#define assert(cond) if(.not. (cond)) print *, "Assert fail: ", CPPSTR(cond)

#define printv1(v1) print *, CPPSTR(v1), (v1)
#define printv2(v1,v2) print *, CPPSTR(v1), (v1), CPPSTR(v2), (v2)
#define printv3(v1,v2,v3) print *, CPPSTR(v1), (v1), CPPSTR(v2), (v2), CPPSTR(v3), (v3)
#define printarray(a) print *, CPPSTR(a); print *, (a)

program t
    implicit none

    integer i, j

    i = 1
    j = 3
    assert(i .lt. 0)
    assert(i .gt. 0)

    printv3(i, j, i+j)
    printv1(([i, j, i+j]))
end program t

Output:

 Assert fail: i .lt. 0
 i           1  j           3  i+j           4
 ([i, j, i+j])           1           3           4

Upvotes: 1

benjfrd
benjfrd

Reputation: 36

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

Upvotes: 2

Related Questions