在 Fortran 中,是 PARAMETER
在运行时或编译时设置属性?
我想知道是否可以在运行时传递数组的大小并将其设置为 PARAMETER
.
这可以做到吗?如果是这样,怎么做?如果不是,为什么?
最佳答案
是的,正如反复回答的那样,命名常量(具有 parameter
属性的对象)必须具有“在编译时已知”的初始值。但是,当您谈论数组的大小时,我会注意其他一些事情。
在声明数组的形状时,很多时候不需要用常量表达式给出边界(其中一个简单的命名常量就是一个例子)。所以,在主程序或模块中
implicit none
...
integer, dimension(n) :: array ! Not allowed unless n is a named constant.
end program
n
必须是常数。然而,在许多其他情况下,n
只需是规范表达式。implicit none
integer n
read(*,*) n
block
! n is valid specification expression in the block construct
integer, dimension(n) :: array1
call hello(n)
end block
contains
subroutine hello(n)
integer, intent(in) :: n ! Again, n is a specification expression.
integer, dimension(2*n) :: array2
end subroutine
end program
也就是说,
array1
和 array2
是显式形状自动对象。出于许多目的,人们并不真正需要命名常量。但是,除了数组大小之外,当然不允许以下内容。
implicit none
integer n, m
read(*,*) n, m
block
! n and m are specifications expression in the block construct
integer(kind=m), dimension(n) :: array ! But the kind needs a constant expression.
...
end block
关于从输入初始化的 Fortran PARAMETER 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31926969/