[英]There any way to get name of Fortran variable?
I like how it's implemented in Python.我喜欢它在 Python 中的实现方式。 Example(Python):
示例(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):
示例(Fortran):
function check(var)
...
if (var < 0) print *, 'Error: var < 0'
...
end function check
There is no way in Fortran to get a variable name dynamically as variable names and types are required at compile time. Fortran 无法动态获取变量名,因为在编译时需要变量名和类型。
You could used Fortran derived types to associate a label to a value:您可以使用 Fortran 派生类型将 label 关联到一个值:
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
For Intel and GNU fortran compilers (by question tags), as well as for many other compilers, you can use a preprocessor ( -cpp
flag).对于 Intel 和 GNU fortran 编译器(按问题标签)以及许多其他编译器,您可以使用预处理器(
-cpp
标志)。
#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: Output:
Assert fail: i .lt. 0
i 1 j 3 i+j 4
([i, j, i+j]) 1 3 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.